0

I'm trying to implement a simple AI system in my DirectX Application. I'm trying to get my Ai to rotate and face the direction I want it to face towards, which I manage to do, but can't figure out how to get it to determine how to rotate to the given direction (i.e should it rotate left or rotate right?).

Here is the code I've got which works out the angle it needs to rotate by to face the direction it's given:

 D3DXVECTOR3 incident = destination - position; float top = D3DXVec3Dot(&incident, &forwardVec); float bottom = sqrt((incident.x * incident.x) + (incident.y * incident.y) + (incident.z * incident.z)) * sqrt((forwardVec.x * forwardVec.x) + (forwardVec.y * forwardVec.y) + (forwardVec.z * forwardVec.z)); float remainingAngle = acos(top/bottom) * 180.0f / PI; 

The forwardVec is a D3DXVECTOR3 of which way the AI is currently facing.

1
  • New approach: rather than a 2 quadrant acos(x), use 4 quadrant atan2(y,x). Not sure how to get your x,y though for you. Commented Jan 9, 2014 at 2:37

3 Answers 3

1

The dot product rule just tells you the shortest angle (which is always less than 180!), not which way to go. Do you have a way to get a direction angle out of a D3DXVECTOR (ie polar form kind of thing?) If so, then you can subtract (desired angle)-(current angle) and if that is within -180 to 180 go counterclockwise; otherwise, go clockwise.

I have a feeling that the cross product might also give a method, but I'd have to sit down with a piece of paper to work it out.

Sign up to request clarification or add additional context in comments.

2 Comments

You're right about the Dot Product. But I'm not too sure what you meant by this "polar form" thing. Any chance you can explain it a bit more please?
Polar form as in vectors -- (distance, direction) rather than (x,y).
0

Let's suppose that straight ahead is 0 and you're counting degrees in a clockwise fashion.

If you need to turn 180 or less then you're moving right.
If you need to turn more than 180 you have to turn left. This turn is a left turn of 360 - value degrees.

I hope this answers your question.

1 Comment

Hi, thanks for the answer, but I don't think this works... in fact, I tried subtracting the 360, but the code I've shown above ONLY works out the angle to rotate it by - it could mean rotate left, or rotate right...
0

The angle between 2 normalized vectors:

double GetAng (const D3DXVECTOR3& Xi_V1, const D3DXVECTOR3& Xi_V2) { D3DXVECTOR3 l_Axis; D3DXVec3Cross(&l_Axis, &Xi_V1, &Xi_V2); return atan2(D3DXVec3Length(&l_Axis), D3DXVec3Dot(&Xi_V1, &Xi_V2)); } 

The returned angle is between -PI and PI and represents the shortest anglular rotation from v1 to v2.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.