Stephen Belanger
Stephen Belanger

Reputation: 6361

How do I find rotation transformed 2D coordinates in XNA?

I'm making an XNA game and have run into a small problem figuring out a bit of vector math.

I have a class representing a 2D object with X and Y integer coordinates and a Rotation float. What I need is to have a Vector2 property for Position that gets and sets X and Y as a Vector2 that has been transformed using the Rotation float. This way I can just do something like;

Position += new Vector2((thumbstick.X * scrollSpeed), -(thumbstick.Y * scrollSpeed));

and the object will move in it's own upward direction, rather than the View's upward direction.

So far this is what I have...I think the set is right, but for += changes it needs a get as well and the answer just isn't coming to me right now... >.>

public Vector2 Position
{
    get
    {
        // What goes here? :S
    }
    set
    {
        X = value.X * (int)Math.Cos(this.Rotation);
        Y = value.Y * (int)Math.Cos(this.Rotation);
    }
}

Upvotes: 2

Views: 8581

Answers (3)

Bill Reiss
Bill Reiss

Reputation: 3460

You can also use the Matrix helper methods to create a Z rotation matrix then multiply your vector by this to rotate it. Something like this:

Vector v1;
Matrix rot = Matrix.CreateRotationZ(angle);
Vector v2 = v1 * rot;

Upvotes: 3

duffymo
duffymo

Reputation: 308813

No, both are incorrect.

A 2D vector transforms like this:

x' =  x*cos(angle) - y*sin(angle)
y' =  x*sin(angle) + y*cos(angle)

where the angle is measured in radians, zero angle is along the positive x-axis, and increases in the counterclockwise direction as you rotate around the z-axis out of plane. The center of rotation is at the end of the vector being transformed, so imagine the vector with origin at (0,0), end at (x,y) rotation through an angle until it becomes a vector with origin at (0,0) and end at (x', y').

Upvotes: 7

Matt Howells
Matt Howells

Reputation: 41266

I think this is a bad idea. Keep all of your objects' X and Y co-ordinates in the same planes instead of each having their own axes. By all means have a Position and Heading properties and consider having a Move method which takes your input vector and does the maths to update position and heading.

Upvotes: 1

Related Questions