Adding Movement
This content is not available in your language yet.
Adding Movement
Section titled Adding MovementNow we are going to add gravity and movement to the player.
-
Go back to your Player scene and attach a script by right clicking the player node and clicking “Attach Script”. Click “Create” as the defaults are what we want. Now if you run your game, you should be able to run around.
-
In Project > Project Settings > Input Map, we will create other keys for the player to use. In the “add new action” box, type in something like left and then click add.
-
On the right, click the plus button and and then press a key to represent it. E.g. for left you could use the left arrow key. Repeat the steps for right and jump.
-
Now go into the Player script and change the
"ui_left"
,"ui_right"
etc. to the inputs you made before. -
You may notice that your player doesn’t flip when going to the left, nor does the animation change from idle to run when you’re moving. To solve this, change your Player script to this:
extends CharacterBody2D## Class for the player, controlled by the user# Constantsconst SPEED = 150.0const JUMP_VELOCITY = -300.0# In-scene nodes@onready var sprite_node = $AnimatedSprite# Runs consistently as much as possible, for physicsfunc _physics_process(delta: float) -> void:# Add the gravity.if not is_on_floor():velocity += get_gravity() * delta# Handle jump.if Input.is_action_just_pressed("jump") and is_on_floor():velocity.y = JUMP_VELOCITY# Get the input direction and handle the movement/deceleration.var direction := Input.get_axis("left", "right")if direction:velocity.x = direction * SPEEDelse:velocity.x = move_toward(velocity.x, 0, SPEED)# Move the playermove_and_slide()# Runs every frame, for anything non-physics like visual thingsfunc _process(_delta: float) -> void:if velocity.x > 0:sprite_node.flip_h = falseelif velocity.x < 0:sprite_node.flip_h = trueif abs(velocity.x) > 0:sprite_node.animation = "run"else:sprite_node.animation = "idle"