简体   繁体   中英

Convert 2 vector2 points to a rectangle in xna/monogame

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 ay, and a rectangle has an x, ay, a width, and a height.

Any help is appreciated! Thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM