In this tutorial, we will see how to move a 2D sprite in a pre-defined path in Godot.
What you will learn
- How to create a path.
- How to make your sprite follow the path
I will be using Godot 3.4.2 for this tutorial. Let’s get started.
Creating a path in Godot
- Add a path2D node to your scene.
- Select the path2D node and click on add points in the path toolbox.
- Add nodes around your scene as required
- Click on close curve if you need a closed path.
Making the sprite follow your path
- Add a Pathfollow2D node as a child of path2D.
- Add your object that needs to follow the path as child of Pathfollow2D.
- Make sure you reset the position of your object to (0,0) or the object will follow the path with a offset.
- Create and add a script to path2D node.
- Copy and paste the code below.
- Play the game and the sprite will follow the path.
extends Path2D var inc=0 var speed=500 # Called every frame. 'delta' is the elapsed time since the previous frame. func _process(delta): inc+=delta*speed $PathFollow2D.offset=inc