Calculating movement direction

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

Im using an AnimationTree to animate the enemies in my game, but I cant find a way to determine the vector that I should pass to it, pointing the movement direction. I copied the code from the path finding sample and it is like this:

func move_along_path(distance):
	var last_point = global_position
	
	var d = last_point.direction_to(path[0])	
	
	$AnimationTree.set("parameters/move/blend_position", d.normalized())
	anim_mode.travel("move")	
		
	while path.size():
		var distance_between_points = last_point.distance_to(path[0])		

		# the position to move to falls between two points
		if distance <= distance_between_points:
			global_position = last_point.linear_interpolate(path[0], distance / distance_between_points)
			return

		# the position is past the end of the segment
		distance -= distance_between_points
		last_point = path[0]
		path.remove(0)
	# the character reached the end of the path
	global_position = last_point
	set_process(false)
	anim_mode.start("idle")

I thought that last_point.direction_to(path[0]) was the one I was looking for, but seems it is not the right way. How can I solve this?

:bust_in_silhouette: Reply From: klaas

Hi,
in your code

var d = last_point.direction_to(path[0])  

should be after

while path.size():
    var distance_between_points = last_point.distance_to(path[0])       

or else an error will occur when the path array is empty.
And it seems your doing nothing with the variable d !?

… or … maybe you want it independent from the pathfinding code …

var last_position:Vector2
var movement_direction:Vector2
func _process(delta):
	movement_direction = last_position.direction_to(global_position)
	last_position = global_position