Coding the playerΒΆ

In this lesson, we'll add player movement, animation, and set it up to detect collisions.

To do so, we need to add some functionality that we can't get from a built-in node, so we'll add a script. Click the Player node and click the "Attach Script" button:


In the script settings window, you can leave the default settings alone. Just click "Create":


If you're creating a C# script or other languages, select the language from the language drop down menu before hitting create.



If this is your first time encountering GDScript, please read Scripting languages before continuing.

Start by declaring the member variables this object will need:

extends Area2D

@export var speed = 400 # How fast the player will move (pixels/sec).
var screen_size # Size of the game window.

Using the export keyword on the first variable speed allows us to set its value in the Inspector. This can be handy for values that you want to be able to adjust just like a node's built-in properties. Click on the Player node and you'll see the property now appears in the "Script Variables" section of the Inspector. Remember, if you change the value here, it will override the value written in the script.


If you're using C#, you need to (re)build the project assemblies whenever you want to see new export variables or signals. This build can be manually triggered by clicking the "Build" button at the top right of the editor.


A manual build can also be triggered from the MSBuild Panel. Click the word "MSBuild" at the bottom of the editor window to reveal the MSBuild Panel, then click the "Build" button.


The _ready() function is called when a node enters the scene tree, which is a good time to find the size of the game window:

func _ready():
    screen_size = get_viewport_rect().size

Now we can use the _process() function to define what the player will do. _process() is called every frame, so we'll use it to update elements of our game, which we expect will change often. For the player, we need to do the following:

  • Check for input.

  • Move in the given direction.

  • Play the appropriate animation.

First, we need to check for input - is the player pressing a key? For this game, we have 4 direction inputs to check. Input actions are defined in the Project Settings under "Input Map". Here, you can define custom events and assign different keys, mouse events, or other inputs to them. For this game, we will map the arrow keys to the four directions.

Click on Project -> Project Settings to open the project settings window and click on the Input Map tab at the top. Type "move_right" in the top bar and click the "Add" button to add the