Getting an angle between two sets of variables inside a script

Godot Version

4.3

Question

I’m working on a turn-based space combat game where each ship is tracked on where it is in space via variables rather than something depicted on-screen. (at least for now, anyway) An important factor in how this will play is that weapons have an arc, points from which they can shoot at from the ship or not depending on how the ship is angled. At first I was doing a simple series of if statements in order to determine the angle the target ship is from the first, but I wanted to change it to something that works in fewer lines so I’m not manually adding in every possible angle. So I search online for a formula which will simplify things, and I eventually get this:
angle_x = tan⁻¹((target_ship_y - ship_location_y) / (target_ship_x - ship_location_x))
Every time I plug it into a calculator it works, outside of the times it’s dividing by zero. Every calculation works as it should So I look around and get it working in Godot. Which in Godot needs to be atan2 in order to work. So it becomes:
angle_x = atan2(target_ship_y - ship_location_y, target_ship_x - ship_location_x)
I’ve tested it with many numbers, all the tan and atan functions, and it all just gets a number between -2 or 2, which confuses me. (I’m using the print command so I can check what’s what) So I dig around and guess that this is because it’s giving me radians rather than degrees, so I add after:
‘angle_x = rad_to_deg(angle_x)’
This gets me…57 degrees when the firing ship is at 0,0 and the enemy ship is at 10,0. At what point is the math here breaking down and producing gibberish? I’ve tried it with tan and atan as well as atan2, making sure nothing was dividing by zero and it still didn’t get me degrees. What am I doing wrong?

This breaks down, because target_x - location_x becomes zero and in the forumla your divide by 0, which tends to go to infinity.

You should rather research the Dot Product and the Cross Product.
See here for example: Angle between Two Vectors Formula | GeeksforGeeks

1 Like

Unfortunately, I couldn’t quite figure out how to get that to work with what I was doing in Godot…but trying to get that to work made me realize I could just use Vector2 as a variable, which has angle_to_point, which I could get working. So thanks for putting me on a path to a solution I could implement.