Rotating Microsoft.XNA.Framework.Rectangle and creating a rectangle based on this rotation?

I tried to do this for a while, but did not have much success. All I want to do is rotate the rectangle, and then create a new rectangle that includes the rotated points.

Anyone have any ideas how this should be done right?

The code I have doesn’t work, but I’m not sure where it is going wrong (the numbers make me think it really works), for example, if I have a rectangle with the following values:

{X:865 Y:76 Width:22 Height:164} 

Result:

 {X:1863 Y:1740 Width:164 Height:22} 

Where is it turned -1.57094443

What I'm doing is grab all four points of the original rectangle and rotate them using this function:

 static public Vector2 RotateVectorAround(Vector2 anchor, Vector2 vector, float rotation) { Matrix mat = new Matrix(); mat.Translation = new Vector3(vector.X - anchor.X, vector.Y - anchor.Y, 0); Matrix rot = new Matrix(); rot = Matrix.CreateRotationZ(rotation); mat *= rot; mat.Translation += new Vector3(anchor.X, anchor.Y, 0); return new Vector2(mat.Translation.X, mat.Translation.Y); } 

Where the "anchor" is the pivot point (I'm not sure if this function sounds mathematically), then I determine the angles of the rotating rectangle as follows:

 Vector2 newTopLeft = new Vector2( Math.Min(Math.Min(topleft.X, bottomRight.X), Math.Min(bottomleft.X, topright.X)), Math.Min(Math.Min(topleft.Y, bottomRight.Y), Math.Min(bottomleft.Y, topright.Y))); Vector2 newBottomRight = new Vector2( Math.Max(Math.Max(topleft.X, bottomRight.X), Math.Max(bottomleft.X, topright.X)), Math.Max(Math.Max(topleft.Y, bottomRight.Y), Math.Max(bottomleft.Y, topright.Y) )); 
+4
source share
1 answer

You can multiply the points of the rectangle by the rotation matrix.

therefore, the given point P during rotation will lead to the point R

where a is rotation

 a = degrees * (PI/180) Rx = Px * cos(a) + Py * -sin(a) Ry = Px * sin(a) + Py * cos(a) 

to rotate around a point, you can align the pivot point before it rotates and add them after rotation again (so that the rotation is almost equal to (0,0)

 Px = Px - PivotX Py = Py - PivotY Rx = Px * cos(a) + Py * -sin(a) Ry = Px * sin(a) + Py * cos(a) Px = Rx + PivotX Py = Ry + PivotY 

I would not use the 3rd dimension here for 2d rotation

in XNA, something like (sorry, no VStudio here):

 point -= pivot point = Vector2.Transform(point, Matrix.CreateRotationZ(angle)); point += pivot 
+6
source

Source: https://habr.com/ru/post/1333942/


All Articles