Search code examples
c#xnaangle

Find Angle Between Two Vectors


I have read some of the duplicate answers about angle between two vectors, but I'm still stuck with my problem. I have two vectors and I want that the angle between them to always be 90 degrees. To achieve that I need to find the angle between them, so that I can subtract or add the correct amount of degrees so that the angle between them always is 90 degrees.

enter image description here

The picture illustrates a sprite and two vectors. How do I find the angle A between them two? I have tried to use this code to get the angle between two vectors, but I must have missed something out, because I don't get the correct results:

        public float GetAngleBetween (Vector2 A, Vector2 B)
    {
        float DotProd = Vector2.Dot (A, B);
        float Length = A.Length () * B.Length ();
        return (float)MathHelper.ToDegrees ((float)Math.Acos (DotProd/Length));
    }

Any input is welcome and thank you in advance for any answers.


Solution

  • I think you may be looking for the Vector2.Dot method which is used to calculate the product of two vectors, and can be used for angle calculations.

    For example:

    // the angle between the two vectors is less than 90 degrees. 
    Vector2.Dot(vector1.Normalize(), vector2.Normalize()) > 0 
    
    // the angle between the two vectors is more than 90 degrees. 
    Vector2.Dot(vector1.Normalize(), vector2.Normalize()) < 0 
    
    // the angle between the two vectors is 90 degrees; that is, the vectors are orthogonal. 
    Vector2.Dot(vector1.Normalize(), vector2.Normalize()) == 0 
    
    // the angle between the two vectors is 0 degrees; that is, the vectors point in the same direction and are parallel. 
    Vector2.Dot(vector1.Normalize(), vector2.Normalize()) == 1 
    
    // the angle between the two vectors is 180 degrees; that is, the vectors point in opposite directions and are parallel. 
    Vector2.Dot(vector1.Normalize(), vector2.Normalize()) == -1 
    

    Is this what you're looking for, or do you need the exact angle?