• 2D
  • Why is my angle calculation inconsistent in _process(delta)?

Hello, I'm trying to make it so that a line aims at the mouse position while still rotating around a pivot that is not part of the line. To do so, I've made my own look_at_mouse() function that calculates the angle between the x axis and the mouse, and then the angle between the line aiming at the mouse through the pivot and the line aiming at the mouse through the line. The sum of the two gives me the exact angle that makes it so that the line aims at my mouse. However, when moving the mouse somewhat close to the line's center, the angle starts going crazy and rotates back and forth for some reason.

I've got a MRE right here if you'd like to test it out: MRE

The problem could be that when values get close to zero, they can jump back and forth between positive and negative values, resulting in large variations in computations based on those small values.

Set the line position to 0, 0. It works fine, I just tested it. The issue was having an offset that was messing up the math.

@cybereality said: Set the line position to 0, 0. It works fine, I just tested it. The issue was having an offset that was messing up the math.

What do you mean by setting the line position to 0,0? If you mean locally, a.k.a. to the pivot, this isn't what I want. I want the pivot to be separate from the line.

Then you can make a child of the pivot and put the line in there. If the line is at a different position the math won't work.

@cybereality said: Then you can make a child of the pivot and put the line in there. If the line is at a different position the math won't work.

I don't understand what you mean here. The line is already a child of the pivot, so you want me to set its position to 0,0? That's means that the line would be on the pivot which I don't want.

Here is another way to do it, but it still doesn't avoid the glitch when getting close to the center:

extends Sprite

func look_at_mouse():
	var mouse_pos = get_global_mouse_position()
	var line_pos = $Line.global_position
	rotation = mouse_pos.angle_to_point(line_pos)

func _process(delta):
	look_at_mouse()

The problem is the rotation also changes the relative position of the line, which means it will glitch out as it is constantly spinning so the values are all messed up. The logic only works right if the pivot is at zero (rotating around the point you are using as a pivot). I can look at it more and see if there is a solution but I'm not sure.