Search code examples
c#math2d

Look in direction of 2d Vector


I am trying to make a simple application that turns a character to look at a vector relative to it's current position.

The rotation value ranges from 0 - 180 and -180 - 0.

Math is not my strong point and I'd appreciate it if C# code examples could be explained, I need a value to set into the rotation variable in the ranges mentioned above.


Solution

  • Use the Atan2() function to convert relative x, y position into angles

    double dx = target.X - actor.X;
    double dy = target.Y - actor.Y;
    double angle = Math.Atan2(dy, dx) * 180 / Math.PI;
    

    Or, with float:

    float dx = target.X - actor.X;
    float dy = target.Y - actor.Y;
    float angle = MathF.Atan2(dy, dx) * 180 / MathF.PI;