开发者

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

I've been trying to do this for a while but haven't had much success. All I want to do is rotate the rectangle and then create a new rectangle which encompasses the rotated points.

Anyone have any ideas how it should be done properly?

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

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

The result is:

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

Where it is rotated -1.57094443

What I do is grab all four points of the original rectangle and rotate them with 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 'anchor' is the pivot point (I'm not sure if this function is mathematically sound), then I determine the corners of the rotated rectangle with this:

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

          开发者_JS百科  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) ));


You can multiply the points of the rectangle with a rotation matrix.

so given point P in a rotation will result in point R

where a is the rotation

a = degrees * (PI/180)

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

to rotate about a point you can substract the pivot point before rotating it and add them after the rotation again (so the rotation is virtually around (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 3'th dimension here for a 2d rotation

in XNA that is something like (sorry no VStudio here):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜