Get direction a sprite is moving in Path2D/Curve2D

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

I need to know if a sprite is moving up, left, down or right as it moves through a Path2D/Curve2d. I have different animations for each direction.

Thanks.

:bust_in_silhouette: Reply From: Skelteon

One solution would be to store the global position the object was in during the last call to _process() or _physics_process(). You could get the difference of the current global position and the previous to get a vector for the change in position, and use its value to determine which animation you want to use.

The code below could be a starting point for this approach. This code doesn’t account for x or y of the change in position being exactly zero; that’s something you’d need to decide how to handle in your own implementation.

var last_position

func _ready():
	last_position = global_position

func _process(delta):
	var animation = get_animation_for(last_position - global_position)
	
	# any other code in _process()
	last_position = global_position
	
func get_animation_for(direction: Vector2):
	# moving left
	if direction.x < 0 and abs(direction.x) > abs(direction.y):
		return left_animation
	
	# moving right
	if direction.x > 0 and abs(direction.x) > abs(direction.y):
		return right_animation
	
	# moving up
	if direction.y < 0 and abs(direction.y) > abs(direction.x):
		return up_animation
	
	# moving down
	if direction.y > 0 and abs(direction.y) > abs(direction.x):
		return down_animation
  

Hope this helps!
-Skel