
2D Player Movement
In this tutorial we will see how to move a 2d player in godot using the CharacterBody2D.
- Godot Engine 4
Introduction
The first things to do is choose a sprite for the player: here is a sprite of link
- Create a new Godot project and create a 2D scene.
- Import the sprite file in Godot by dragging and dropping.
- Create a CharacterBody2D
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:
StaticBody2D: Designed for collidable objects that do not move, such as walls, floors, or static obstacles. They do not consume physics processing power unless moved manually.
RigidBody2D: Controlled entirely by Godot’s physics engine. You apply forces, impulses, and torque, letting the engine calculate realistic responses (e.g., tumbling crates, bouncing balls).
CharacterBody2D: Controlled via code. This node gives you complete, frame-by-frame authority over collision response, slope handling, and movement logic without fighting a dynamic physics simulation. It is the gold standard for player avatars, platformer characters, and AI monsters.
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.
- 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()
- 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
