Home > Back-end >  How to calculate rotation needed to face an object
How to calculate rotation needed to face an object

Time:12-29

In case of duplicate - i already readed other posts from stackoverflow. Most of them are asociated with Unity3D, and a lot of them are using keywords like theta/omega .. ect. I can't understand any of that stuff. Also, i have 0 knowledge of those formula symbols so i understand 0% of what i readed.

I experiment making a bot for a video game, the only thing im stuck with is how to get the needed rotation degree till i face the given cordinate. Here i made quick example of my question in programming.

Things that i know in the situation:

  1. Player1 position
  2. Player1 rotation
  3. Player2 position (i need to face this player)

2D map of the situation. Click here

And here is how it looks in c#

using System;
                    
public class Program
{
    // Player 1 cordinates
    public static float p1x = 2;
    public static float p1y = 3;
    public static float p1rotation = 0; // In degrees 0-360
    
    // Player 2 cordinates
    public static float p2x = 6;
    public static float p2y = 4;
    
    // Player 1 needed degree to face Player 2
    public static float needed_distance;
    
    public static void Main()
    {
        needed_distance = ??; // no clue how to get this value ...
        Console.WriteLine("The needed distance is: " needed_distance);
        
    }
}
Also you can edit this code and execute it here directly -> https://dotnetfiddle.net/b4PTcw

Please don't mark this as a duplicate, my math skills are even below zero. I can understand better if someone tries to answer me using the example that i made.

CodePudding user response:

You are looking for Math.Atan2 method:

private static float Rotation(float p1x, float p1y, float p2x, float p2y) =>
  (float)(Math.Atan2(p1x - p2x, p2y - p1y) * 180.0 / Math.PI   630) % 360.0f;

private static float Distance(float p1x, float p1y, float p2x, float p2y) =>
  (float)Math.Sqrt((p1x - p2x) * (p1x - p2x)   (p1y - p2y) * (p1y - p2y));

Demo:

Console.WriteLine(Rotation(2, 3, 6, 4));

Outcome:

194.0362548828125

So, if player #1 initial rotation1 = 0 (s)he needs to turn at ~ 194 degree. In case of player #1 arbitrary initial rotation1:

float rotation1 = ...;

float requiredRotation = (Rotation(p1x, p1y, p2x, p2y) - 
   (rotation1 % 360f)   360f) % 360f;    
  • Related