Rotation Problem

Started by
5 comments, last by dries123 15 years, 4 months ago
//The Mouseposition.
Vector2 m_EndPos = m_Input.MousePos;
//The current position of the player.
Vector2 m_CurPos = m_Player.Position;
//Normalised directional vector.
Vector2 m_Direction = m_EndPos;
m_Direction.Normalize();

float InvCos = (float)Math.Acos(m_Direction.X / 1);
float Angle = MathHelper.TwoPi - InvCos;
m_Player.Rotation = Angle;
I've got the code you see above and it should rotate my character to face the mouseposition. The code is in C#. Can anyone tell me what's wrong with it.
Advertisement
You should look into atan2().

The code should be something like this I think

Vector2D diff = playerPos - mousePos;
float rotation = atan2(diff.y / diff.x);
There're are a few little misstakes:

1. Vector2 m_Direction = m_EndPos;
This should be: Vector2 m_Direction = m_EndPos - m_CurPos;

2. float InvCos = (float)Math.Acos(m_Direction.X / 1);
Almost correct :) I think you want to take the x-axis as reference. Than the cosinus of the angle is defined as:
cos(angle)=dot(m_Direction,(1,0))=m_Direction.X*1+m_Direction.Y*0=m_Direction
Your code will look like:
float InvCos = (float)Math.Acos(m_Direction.X);

3. float Angle = MathHelper.TwoPi - InvCos;
InvCos will always be between [0...PI] (180 degree). If you want to map this to [0..2*PI] you have to consider if your direction is left or right of your reference axis. In this case your code should look like:
float Angle=0;
if(mDirection.Y<0) { //right of your reference axis
Angle = MathHelper.TwoPi - InvCos;
} else { // left of your reference axis
Angle = InvCos;
}

--
Ashaman


Thank you very much for helping me out with this. :)


if you are going to use code with a division remember to have a check for divide by zero and handle it seperately.


dy/dx you have to check if dx is 0 and if so the angle is two of the multiples of pi/2 (depending on which quadrant system you are using).
--------------------------------------------[size="1"]Ratings are Opinion, not Fact
Dealing with angles is always messy. Can't you simply store the orientation of the player as a vector? That approach usually makes life easier.
I can calculate the angle using vectors I suppose, but xna can't work with them for rotations as far as I know.

This topic is closed to new replies.

Advertisement