How to rotate a RigidBody2D continuously

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

I have an enemy that turns towards the player I used the angle_to_point () function to calculate the angle of the enemy relative to the player’s position and saved the value in a variable, each frame the enemy looks towards the player but when the value of the player’s angle is negative (jumps from 3.0 to -3.0) the enemy makes a full turn instead of following the player continuously Here is the code in the RigidBody2D(the enemy):

onready var player = get_parent().get_node("player")

func _process(delta):
  var angle_pos = player.position.angle_to_point(get_global_position())


  # this just means set the angular velocity towards the player if 
  # it's angle to point value is less than the rotation of the enemy
  if stepify(rotation, 0.05) > stepify(angle_pos, 0.05):

  if stepify(rotation, 0.05) < stepify(angle_pos, 0.05):

here I leave a video that shows the problem:

:bust_in_silhouette: Reply From: klaas

the rotations go from -PI to 0 to PI. if youstep over the -PI PI border your if is failing because the rotation difference is actualy small but the sign has swapped.

I think it must be something like

var angle_pos = player.get_angle_to( global_position )
#calculate the absolute difference
var dif = abs( rotation - angle_pos )
#check if the PI border is crossed
if dif > PI:
	angle_pos *= -1

#your code comes here
if angle_pos > rotation:
	rotate( 0.01 )
	rotate( -0.01 )

Yes! it works! here is the code:

var player_location = player_node.position

var player_angle_point = stepify(player_location.angle_to_point(get_global_position()), 

var enemy_rotation = stepify(rotation, 0.05)

rotation_speed = 1
var dif = abs( enemy_rotation - player_angle_point )	

if dif > PI:
	rotation_speed *= -1		

if player_angle_point  > enemy_rotation:
elif player_angle_point < enemy_rotation:

I had done it with rotation = player_angle_point but I wanted to rotate the enemy with the physics so as not to superimpose the transform on the physics, Thanks!

vnmk8 | 2020-09-17 22:22