Vector2 angle_to angle incorrect

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By pm101

Hi

I’m trying to use angle_to to set the rotation of an object to face the player but it is giving a much smaller value than expected. I’ve added some debug output that you can see in the image . It should be about -45 degrees (-0.78 radians) as I’ve positioned the player threabouts but you can see that value is only about -0.1 radians.

What’s going on?

I might be an idiot but I thought this worked before

image:

code:

func doShoot():
		var angle =  self.global_position.angle_to(player.global_position);
		self.rotation = angle
		
		$Label.text = Vector2String("robot",self.global_position) + Vector2String("player",player.global_position)
		$Label.text += "angle = " + str(angle)

func Vector2String (nam, vec):
	return nam + " = (" + str(vec.x) + "," + str(vec.y) + ")\r\n"

Note: if I do it myself (using atan2) its fine, but rather not as I’m trying to tut a pre-mid school student

this is ok:

	var comp = enemy.global_position - self.global_position
	
	var angle =  atan2(comp.y,comp.x)
	self.rotation = angle
:bust_in_silhouette: Reply From: Ninfur

In the example using angle_to, you are getting the angle between the two entities global position. This angle will depend on how far the entities are from the origin of the scene.

Visual example. In this case the angle between the vectors will be really small.

What you want to do is get the angle of the difference vector, similar to what is done in the atan2 example.

I believe you could do something like this:

var diff = enemy.global_position - self.global_position
diff.angle()

Update:
After looking through the docs, you may be able to use angle_to_point instead of angle_to.

:bust_in_silhouette: Reply From: Pomelo

There is no error in the code. The problem is a math problem of understanding what the angle between vectors are. looking at your image, the 2 vectors are (650, 25) and (750, 50) (rounded up a bit). Remember that vectors “come” from the origin (0, 0). If you plot/draw them (just a line joining (0, 0) and the (650, 25) or (750, 50) ) you will see they are almost paralel vectors, thus the small angle between them.

What you want is the angle between the vector that goes from (650, 25) to (750, 50) and the positive x axis. You could do that in many ways, but I am pretty sure .angle_to_point() will do the trick!

When I started writing, Ninfur awnser wasnt there. Its the same awnser, so dont bother reading it again haha

Pomelo | 2022-06-11 13:17

1 Like

Thanks