Changing Animation length skips beginning of animation

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

I have a question about AnimationPlayer seemingly skipping. I have a sample project where I can make a sprite move 1, 2, or 3 units back and forth. I use AnimationPlayer to handle the position change. The image below is what it looks like if I make my sprite move 1 unit three times, then 2 units three times, and finally 3 units three times.

https://i.imgur.com/lo14Pvq.gif

If I change the animation length, it seems like the first time the animation is played, it skips the first x seconds where x is the old animation time. So for example, after a “move 1” animation (.5 seconds) and I change the animation length for a “move 2” animation (1 second), the first .5 seconds of the “move 2” animation are skipped. However, subsequent plays of the animation work if I don’t change the animation length again.

Here is what the code looks like.

func _input(event):
	if event.is_action_pressed("move_1"):
		move(1)
	elif event.is_action_pressed("move_2"):
		move(2)
	elif event.is_action_pressed("move_3"):
		move(3)


func move(distance: int):
	var animation = $AnimationPlayer.get_animation("Move")
	animation.length = distance * .5
	for i in distance + 1:
		var key = $Mover.position + Vector2(i, 0) * 64 * direction
		animation.track_insert_key(0, i * .5, key, .5)
	$AnimationPlayer.play("Move")
	direction = -direction

Is there something simple I am overlooking?