For a node that moves by repeatedly setting their position (such that velocity isn't actually known, like it would for KinematicBody2D
or RigidBody2D
), you can determine the direction an enemy is going by comparing its current position and its position from the last frame.
var _position_last_frame := Vector2()
var _cardinal_direction = 0
func _physics_process(delta):
# Get motion vector between previous and current position
var motion = position - _position_last_frame
# If the node actually moved, we'll recompute its direction.
# If it didn't, we'll just the last known one.
if motion.length() > 0.0001:
# Now if you want a value between N.S.W.E,
# you can use the angle of the motion.
# I came up with this formula last time I needed it:
_cardinal_direction = int(4.0 * (motion.rotated(PI / 4.0).angle() + PI) / TAU)
# And now you have it!
# You can even use it with an array since it's like an index
match _cardinal_direction:
0:
print("West")
1:
print("North")
2:
print("East")
3:
print("South")
# Remember our current position for next frame
_position_last_frame = position
I used a fancy formula here but if you just need the motion
vector, you can also work out something that suits you, by checking motion.x
and motion.y
.