Sign in to follow this  

simple object follow rotation calculations

Recommended Posts

I am trying to simply have one objects sprite face the direction of its movement. the code i have (below) does not seem to change the rotation at all outside pi/4 and 5pi/4.

//vector to target
Vector2 toTarget = (seekTarget.position - Game1.mapOffset) - (enemy.position - Game1.mapOffset);
//vector to add to heading to change direction of movement
m_vTurn = toTarget - m_vHeading;

//Angle to add to sprite's draw rotation
double turnAngle = Math.Acos(Vector2.Dot(toTarget, m_vHeading)) ;
if (turnAngle > 0)
//make sure it doesnt turn faster than its max turn rate
m_vTurn = Vector2.Clamp(m_vTurn, new Vector2(-(float)m_dMaxTurnRate), new Vector2((float)m_dMaxTurnRate));
//cap at max turn
if (turnAngle > m_dMaxTurnRate)
turnAngle = m_dMaxTurnRate;

//if dot product of the two vectors is neg then target is behind object and needs to turn until it is facing target
m_vTurn = new Vector2((float)m_dMaxTurnRate);
//change direction of movement
m_vHeading += m_vTurn;

//inside this statement tries to set its rotation to the direction it is moving
if (toTarget.X > .5f || toTarget.Y > .5f)
enemy.rotation += (float)turnAngle;
if (enemy.rotation > Math.PI * 2)
enemy.rotation = 0 + enemy.rotation - (float)Math.PI * 2;


so basically to sum up the code, im taking the dot of 2 vectors, one is the objects heading direction and the other is the vector pointing towards the target. My objective is to take the angle that it turns and add it to the rotation.

another method I tried to use is below where i just take a vector (1,0) and the heading vector and dot them to get an angle to use as rotation (shown below) but i'm having problems with that as well. if anyone has any suggestions I would be so greatful.

enemy.rotation = -(float)Math.Acos(Vector2.Dot(new Vector2(0,1), m_vHeading))

Share this post

Link to post
Share on other sites
Original post by karwosts
Are you aware of the atan2 function? It's much more convenient than trying to work out all the right trig quadrants. It might help you here.

I am not, thank you I will investigate. Thanks karwosts!

I still wouldnt mind learning why what I did doesn't work, if anyone cares to explain. :/

Is it because I am using an inverse trig function to get the value and it only works up to pi? so then i should use different functions per quadrants?

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this