我有一些代码可以检测点击并拖动动作的起点和终点,并将其保存到2个vector2点。然后我使用此代码转换:
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,宽度和高度。
任何帮助表示赞赏!感谢
答案 0 :(得分: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);
}