0 votes

I have an enemy that turns towards the player I used the angletopoint () 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: https://youtu.be/bzrN_YvcVhA

in Engine by (452 points)
edited by

1 Answer

0 votes
Best answer

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 )
by (4,078 points)
selected by

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 = playeranglepoint but I wanted to rotate the enemy with the physics so as not to superimpose the transform on the physics, Thanks!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.