How to animate a node from a fixed position to a random one?

Godot Version

4.2.2

Question

I need to animate my node from a position below the bar to a random point that is created by code. What I want is to achieve an animation that looks fluid until reaching the random position. image 1 image 2

I know I could achieve the animation with the AnimationPlayer, but I don’t know how to assign the random position each time (there are 5 nodes that need to be moved). The nodes are created and assigned their position in the random_location() function

You can animate the position (to a certain fixed placeholder position).
Then, via code, dymanically modify the value of the keyframe of that animation (use Animation.track_set_key_value) to your random position, and then play the animation.

In this case I made it so that when I press the space bar, the animation resets and goes back to 0,0 and then to a different random position every time.

This is the result.

1 Like

You can use a tween instead of the animation player.

var final_position := Vector2(rand_x, rand_y)
var starting_position := Vector2.ZERO
var duration: float = 2.0 # in seconds

var tween := create_tween()
tween.tween_property(objInstance, "position", final_position, duration).from(starting_position)
2 Likes

Thank you for your reply. I’m going to choose the tween version because it’s more comfortable for me in this case, but know that both options are viable.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.