My rotation code goes crazy, randomly

Godot Version

4.2.1

Question

I’m trying to get a turret to rotate toward enemies, but not instantaneously like look_at and I’m trying to use the same code to make my creeps look toward where they want to be.

Here’s the code:

func target_position( node : Node2D, position : Vector2, delta : float ):
	
	var target_angle = node.position.angle_to_point( position )
	var delta_rotation = rotate_toward( node.rotation, target_angle, delta )
	
	if abs( target_angle - node.rotation ) < delta_rotation:
		node.look_at( position )
	else:
		node.rotate( delta_rotation )
  • The node is either the turret or the creep.
  • The position is the target (a destination for the creeps, or the nearest (within range) creep.position for the turret)
  • The delta is the delta from _process_physics multiplied by 0.00000000001

The issue is that randomly, the turret and/or creep randomly go into spins.

Note that the creeps target is initially their current y but with an x of 1990. The target is updated by either shape casting and ‘seeing’ it, or, at a specific distance (after the shape cast should have seen the target) it is set to the bottom right corner. In the video, the shape casting will always see the target. This seems to be where the creeps start/stop spinning.

Related: the 0.00000000001 seems way too small given how fast the turret actually turns to face a creep.

Related: the tower sometimes disappears after spinning a while (I was lucky to catch it in the video). It still exists in the Remote tree and has healthy values in transform (rotation = 0), and there’s no error logged indicating why it is suddenly invisible.

Video of issue:

Thanks,
Brian.

For rotation stuff, try quaternions. I’ll go look for a ref.

1 Like

Another way without quats:

1 Like