Topic was automatically imported from the old Question2Answer platform.
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())
set_angular_velocity(0)
# 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):
set_angular_velocity(-1)
if stepify(rotation, 0.05) < stepify(angle_pos, 0.05):
set_angular_velocity(1)
Hi,
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 )
else:
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()),
0.05)
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:
set_angular_velocity(rotation_speed)
elif player_angle_point < enemy_rotation:
set_angular_velocity(-rotation_speed)
else:
set_angular_velocity(0)
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!