2017-07-22 72 views
2

我有一些代码可以检测点击拖动动作的开始和结束点,并将其保存到2个vector2点。然后,我使用此代码进行转换:将2个vector2点转换为xna/monogame中的矩形

public Rectangle toRect(Vector2 a, Vector2 b) 
{ 
    return new Rectangle((int)a.X, (int)a.Y, (int)(b.X - a.X), (int)(b.Y - a.Y)); 
} 

上面的代码不起作用,并且使用谷歌搜索,迄今为止还没有定论。 任何人都可以请给我提供一些代码或公式来正确地转换此?
注:vector2具有x和y,矩形具有x,y,宽度和高度。

任何帮助表示赞赏!谢谢

回答

4

我想你需要有额外的逻辑来决定使用哪个向量作为左上角和哪个向右使用。

试试这个:

public Rectangle toRect(Vector2 a, Vector2 b) 
    { 
     //we need to figure out the top left and bottom right coordinates 
     //we need to account for the fact that a and b could be any two opposite points of a rectangle, not always coming into this method as topleft and bottomright already. 
     int smallestX = (int)Math.Min(a.X, b.X); //Smallest X 
     int smallestY = (int)Math.Min(a.Y, b.Y); //Smallest Y 
     int largestX = (int)Math.Max(a.X, b.X); //Largest X 
     int largestY = (int)Math.Max(a.Y, b.Y); //Largest Y 

     //calc the width and height 
     int width = largestX - smallestX; 
     int height = largestY - smallestY; 

     //assuming Y is small at the top of screen 
     return new Rectangle(smallestX, smallestY, width, height); 
    } 
+0

谢谢!代码工作得很好! –

+0

您正在寻找'smallestY',但代码'int smallestY =(int)Math.Min(a.X,b.X);'这是不正确的 – MickyD

+0

@MickyD编辑纠正错误,感谢您发现一个! –