Convert 2 vector2 points to a rectangle in xna/monogame

▼魔方 西西 提交于 2019-12-11 01:40:07

问题


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));
}

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.

Any help is appreciated! Thanks


回答1:


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.

Try this:

    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);
    }


来源:https://stackoverflow.com/questions/45259380/convert-2-vector2-points-to-a-rectangle-in-xna-monogame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!