Atan2 Issue


I am writing a program using directx and I have come across a problem.

I have several models which display pathfinding behaviour but I am struggling to make the models face the direction in which they are moving.

So far my thoughts on tackling this problem are...

1) Get the distance between the model position and the goal position
2) Normalise this vector to create a direction
3) Use atan2 on the direction vector to create a rotation
4) Rotate the model the relevant amount of radians

As yet I have the models navigating towards the goal position using the direction vector created and this is working fine. When I attempt to add the rotation the results seem eratic with the model sometimes being orientated correctly. It seems like they are fine when heading in a +Z and/or a +X direction.

Although this is 3D space I am using a Y up system so have subbed the Y variables with Z. Not at my comp but from memory the code I have is...

Vector3D distance = m_position - goalNode->GetPosition();
D3DXVec3Normalize(&distance, &distance);
float rotation = atan2(distance.z, distance.y);
D3DXMatrixRotationY(&m_rotateY, rotation);

After this the model is transformed and rotated by m_rotateY and other transform matrices.

If anyone has any thought, suggestions or questions please let me know

results seem eratic
How exactly erratic? Does it rotates at random angles, or it is always backward?
Shouldn't it be atan2(distance.z, distance.x);?
Sorry my typo

I do have it as atan2(distance.z, distance.x)

In terms of erratic, the rotation of the model is not consistent with the direction (i.e it is not always 90 degrees offset) it seems to be random. I am yet to establish a pattern with this but in general I would say the facing direction is correct when moving in a positive direction both X and Z axis. Dont know if this has anything to do with it?
Well, the question here is: how do you use the matrix you create? I mean in terms of computing the angle - it is fine (although I think you should subtract the object position from the goal position and not the other way around). The error should reside somewhere else in your code. If you show how you use the matrix further in your code I think we will be able to help you track down the problem.
Thanks for the input

All solved now.

The problem was with the result returned from atan2. The rotation is returned as an angle with co-ords (1, 0) being zero and then positive rotation being counter clockwise from that vector. Negative rotation being clockwise.

D3DMatrixRotationY rotates around a Y axis in a clockwise direction. Along with the starting direction vector of my model being (0, 0, 1) it was confusing to figure out what was happening.

To account for the anticlockwise rotation of the return value of atan2 I negated the result. Then added a further 90 degree rotation clockwise to account for the model offset and all works fine (fingers crossed)

Topic archived. No new replies allowed.