Beginnergodot
Beginner

2D Player Movement

In this tutorial we will see how to move a 2d player in godot using the CharacterBody2D.

Prerequisites / Tools :
  • Godot Engine 4
Nicolas Perdu
Written by Nicolas PerduSoftware engineer

Introduction

The first things to do is choose a sprite for the player: here is a sprite of link

Why CharacterBody2D?

When building a 2D game in Godot, choosing the correct node for interactive entities is the foundation of your physics architecture. Godot provides three primary 2D physics body types, each tailored to specific gameplay responsibilities:

Key Improvements in Godot 4

If you are transitioning from Godot 3 or upgrading an existing project, CharacterBody2D replaces the old KinematicBody2D node. Godot 4 streamlined the API to make movement code cleaner and less error-prone.

  1. Built-In velocity Property

In Godot 3, developers had to declare and manage custom vector variables for speed and direction. In Godot 4, velocity is a first-class, built-in property on CharacterBody2D (Vector2). 2. Simplified move_and_slide()

Moving a character body in Godot 3 required passing parameters and capturing return values: GDScript

Godot 3 Syntax (Deprecated)

velocity = move_and_slide(velocity, FLOOR_NORMAL)

In Godot 4, move_and_slide() reads the node’s internal velocity property, executes the collision detection and sliding logic, and updates velocity automatically when colliding with walls or floors. No arguments or return assignments are necessary: GDScript

Godot 4 Syntax

velocity = Vector2(200, 0) move_and_slide()

  1. Automatic Delta Handling inside move_and_slide()

The move_and_slide() method automatically factors in the physics frame delta time when modifying position.

Note on Delta Usage: You do not multiply velocity by delta when passing it to move_and_slide(). However, you do still multiply frame-rate-dependent forces like acceleration or gravity by delta when updating the velocity vector itself (e.g., velocity.y += gravity * delta).

Download The full project

You can download the complete project: 2DPlayerMovement.7z