Godot 2D. Player movement

Submitted by tech4life on

One of the most important points in our games is the movement of our player. In this case we are going to explain a simple and easy way to generate movement in a 2D game. We are going to explain the mechanics that we used in our last game, in which we pilot a spaceship and must avoid meteorites. We decided that the player could only move left and right, which simplifies the whole process a little, although it is a good starting point for other types of games.

Create controls

Our game is designed to be played on mobile phones and tablets, so the controls we decided to do were with on-screen buttons.

As you can see, we created two buttons, of type TouchScreenButton. We linked two signals to each of them, one when the button is pressed and another when it is released.

Logic for the controls

In each of these 4 functions we add the following code:

To centralize the movement in a single function, we call our "move" function, passing it a 0 when we have released the button and do not want movement, and then indicating when pressing a button if we want to go to the right (1) or to the left (-1).

Our "move" function only marks the movement in a Global variable that we can use in any other scene. In our case, the player's movement will be managed by the player's own scene script.

Player movement

So let's see the magic of movement in the player's script:

As you can see, the code is very simple. In the _physics_process function, we call a function that will generate the movement. To move the player in this case, just modifying the position variable is enough. As we have mentioned, we will only modify the x coordinate of the position, since we will only move from left to right.

To do this, we delegate the movement to a new function that will calculate the new position based on a speed variable that tells us how much we will move, and this function will check if we have reached the end of the screen, and if so, it will set the final position of the screen, otherwise our player would leave the scene and that is something we do not want.

Necessay variables

And these are the variables for the player, with the start and end of screen positions and the speed:

As you can see, it is a very simple way to generate movement for a 2D game.

 

Nivel