0

I've gone through a lot of questions online for the last few hours trying to figure out how to calculate the rotation between two vectors, using the least distance. Also, what is the difference between using Atan2 and using the dot product? I see them the most often.

The purpose is to rotate in the y axis only based on differences in X/Z position (Think top down rotation in a 3D world).

  1. Option 1: use Atan2. Seems to work really well, except when it switchs the radians from positive to negative.

        float radians = (float)Math.Atan2(source.Position.X - target.Position.X, source.Position.Z - target.Position.Z);
    
        npc.ModelPosition.Rotation = new Vector3(0,
            npc.ModelPosition.Rotation.Y + (radians), 
            0);
    

This works fine, except at one point it starts jittering then swings back the other way.

  1. Use the dot product. Can't seem to make it work well, it ALWAYS turns in the same direction - is it possible to get it to swing in the least direction? I understand it ranges from 0 to pi - can I use that?

        float dot = Vector3.Dot(Vector3.Normalize(source.Position), Vector3.Normalize(target.Position));
        float angle = (float)Math.Acos(dot);
    
        npc.ModelPosition.Rotation = new Vector3(0, 
            npc.ModelPosition.Rotation.Y + (angle), 
            0);
    

Thanks, James

James F
  • 535
  • 9
  • 26
  • http://stackoverflow.com/questions/5188561/signed-angle-between-two-3d-vectors-with-same-origin-within-the-same-plane-reci – gareththegeek May 13 '13 at 09:19

1 Answers1

0

You calculate two different angles:

Visualization

Angle alpha is the angle calculated with atan2 (which equals opposite side / adjacent side). Angle beta is the one calculated with the dot product.

You can achieve similar results (as with atan) with the dot product with

angle = acos(dot(normalize(target - source), -z))

(-z is the unit vector in negative z direction)

However, you will lose the sign.

Nico Schertler
  • 32,049
  • 4
  • 39
  • 70