# Rotation of Player

This topic is 896 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Whats up gents,

Trying to program a rotation from my mainPlayer to an enemyNPC.

3D coordinate system, positive z is the up vector, enemies and player have position and direction vector.

i believe i have the math correct. i was just wondering is there a way to compute this with just the cross product?

get cross product between main player facing and up vector

Vector3 cross = mainPlayer.Facing.Cross(new Vector3(0,0,1));

get the vector from enemy to mainPlayer

Vector 3 inBetween = new Vector3((enemy.Position.X - mainPlayer.Position.X, enemy.Position.Y - mainPlayer.Position.Y, enemy.Position.Z - mainPlayer.Position.Z);

compute the angle via dot product

float dot = cross.dot(inBetween);
if (dot <= 0.0f)
turn right
else
turn left

Thanks for any input or help

##### Share on other sites

That seems sensible. Work out which direction is 'right' work out if the enemy is on the left or the right. If it's on the right turn right, if it's on the left turn left. I quite like it and I'm ashamed to say I would have definitely over complicated the problem if I had to solve it.

I don't see any major issues with your solution but when the dot product is 0 then you are either directly facing the enemy or have your back to the enemy. You could also use the 'facing' vector dot with the inBetween vector to work out if you are facing the enemy and stop turning.

There are other ways to do this that might be more appropriate depending on how your game is. If your solution doesn't meet with your requirements then you can use a 'look at' matrix type approach but then you still have to deal with actually rotating to that orientation.

##### Share on other sites

Ah thanks a bunch for your input Nanonah. Really appreciate the help and confirmation. :)

##### Share on other sites

There is a relation between angle and position with the dot product, but that alone does not tell you the angle. If you want to rotate towards an NPC or any point in 2d space(along the UP axis, Y in D3D, z in OpenGL), you can use the arcos of the geometric definition of the dot product.

That is cos(theta) = Dot(vec1, vec2)/(mag(vec1) * mag(vec2)).

$cos(theta) = \frac{A \cdot B}{\left \| A \right \|\left \| B \right \|}$

Take the arcos of the right side to get the angle between the two facing vectors.

Or

$arcos(\frac{A\cdot B}{\left \| A \right \|\left \| B \right \|}) = \Theta betweenvectors$

That is a good place to start.

1. 1
2. 2
Rutin
20
3. 3
khawk
16
4. 4
A4L
14
5. 5

• 11
• 16
• 26
• 10
• 11
• ### Forum Statistics

• Total Topics
633756
• Total Posts
3013707
×