将2个vector2点转换为xna/monogame中的矩形 [英] Convert 2 vector2 points to a rectangle in xna/monogame
问题描述
我有一些代码可以检测单击并拖动动作的起点和终点,并将其保存到2个vector2点.然后,我使用以下代码进行转换:
I have some code which will detect the start and end point of a click-and-drag action, and will save it to 2 vector2 points. I then use this code to convert:
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));
}
上面的代码不起作用,无法使用Google搜索,到目前为止,尚无定论.
任何人都可以向我提供一些代码或公式来正确转换此代码吗?
注意:vector2具有一个x和y,一个矩形具有x,一个y,一个宽度和一个高度.
The code above does not work and googling, so far has come up inconclusive.
Could anyone please provide me with some code or a formula to properly convert this?
Note: a vector2 has an x and a y, and a rectangle has an x, a y, a width, and a height.
感谢您的帮助!谢谢
推荐答案
我认为您需要在其中具有附加逻辑,以便确定将哪个向量用作左上角,并将哪个向量用作右下角.
I think you need to have additional logic in there to decide which vector to use as the top left and which to use as the bottom right.
尝试一下:
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);
}
这篇关于将2个vector2点转换为xna/monogame中的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!