CharacterBody2D & move_and_slide
Godot has four kinds of 2D physics object. Picking the right one is the first design decision for anything that moves:
| Node | Moved by | Use it for |
|---|---|---|
StaticBody2D |
nothing (or your code, rarely) | floors, walls, platforms that don't move |
AnimatableBody2D |
your code or an AnimationPlayer; pushes what it touches |
moving platforms, doors, elevators |
RigidBody2D |
the physics engine (forces, gravity, impulses) | crates, balls, ragdoll pieces, debris |
CharacterBody2D |
your code, with collision handled for you | players, enemies, NPCs: anything that needs tight, predictable control |
Area2D |
nothing; it only detects overlaps | pickups, triggers, hit boxes (see Areas, Collision Layers & Raycasts) |
A CharacterBody2D is kinematic: physics never pushes it around. Each physics frame you set its velocity property and call move_and_slide(). The method moves the body by velocity * delta, stops it at walls, slides it along surfaces, and updates is_on_floor(), is_on_wall() and is_on_ceiling(). You never multiply by delta yourself for the movement: move_and_slide() does it.
Migrating from Godot 3:
KinematicBody2DbecameCharacterBody2D, andmove_and_slide(velocity, Vector2.UP)became a call with no arguments.velocity,up_directionand the floor settings are now properties on the body.
The body needs a shape
A physics body without a CollisionShape2D (or CollisionPolygon2D) child collides with nothing, and the editor shows a yellow warning triangle next to it. A typical player scene:
Player (CharacterBody2D) player.gd
├── Sprite2D
└── CollisionShape2D shape: RectangleShape2D or CapsuleShape2DSaved as a .tscn file, the shape is a sub-resource of the scene:
[gd_scene load_steps=3 format=3]
[ext_resource type="Script" path="res://player.gd" id="1_p"]
[sub_resource type="CapsuleShape2D" id="CapsuleShape2D_1"]
radius = 7.0
height = 24.0
[node name="Player" type="CharacterBody2D"]
script = ExtResource("1_p")
[node name="Sprite2D" type="Sprite2D" parent="."]
[node name="CollisionShape2D" type="CollisionShape2D" parent="."]
shape = SubResource("CapsuleShape2D_1")In the editor:
- Create a new scene and choose Other Node > CharacterBody2D as the root. Rename it
Player. - Add a
Sprite2Dchild and drag a texture (for exampleicon.svg) into its Texture property. - Add a
CollisionShape2Dchild. In the Inspector, click Shape > New CapsuleShape2D and drag the orange handles to fit the sprite. - Attach a script to
Player. The Template menu offers CharacterBody2D: Basic Movement, a working left/right/jump controller to start from.
The examples on this page build the same nodes in code, because there is no editor here. The pattern is always: create the node, create the shape resource, add the shape as a child.
Falling and landing
Gravity is not applied to a CharacterBody2D automatically. Add it to velocity.y each physics frame while the body is in the air (in 2D, +y is down). The ground here is a StaticBody2D whose top edge is at y = 90:
extends Node2D
# frames: 30
const GRAVITY := 980.0 # pixels/s², the project default
var player: CharacterBody2D
var landed := false
func make_box(size: Vector2) -> CollisionShape2D:
var shape := RectangleShape2D.new()
shape.size = size
var cs := CollisionShape2D.new()
cs.shape = shape
return cs
func _ready():
var ground := StaticBody2D.new()
ground.add_child(make_box(Vector2(400, 20)))
ground.position = Vector2(0, 100) # top surface at y = 90
add_child(ground)
player = CharacterBody2D.new()
player.add_child(make_box(Vector2(16, 16)))
add_child(player) # starts at (0, 0), bottom edge at y = 8
func _physics_process(delta):
if landed:
return
if not player.is_on_floor():
player.velocity.y += GRAVITY * delta
player.move_and_slide()
var frame := Engine.get_physics_frames()
if player.is_on_floor():
landed = true
print("landed at frame ", frame, ": y = ", snappedf(player.position.y, 0.01), ", vy = ", player.velocity.y)
elif frame % 5 == 0:
print("frame ", frame, ": y = ", snappedf(player.position.y, 0.01), ", vy = ", snappedf(player.velocity.y, 0.01))frame 5: y = 4.08, vy = 81.67
frame 10: y = 14.97, vy = 163.33
frame 15: y = 32.67, vy = 245.0
frame 20: y = 57.17, vy = 326.67
landed at frame 25: y = 81.99, vy = 0.0
Things to notice:
- The body stops at y ≈ 82, not exactly 82 (90 minus half its 16 px height).
move_and_slide()keeps a tiny gap, the safe margin (safe_margin, 0.08 px by default), so the next frame doesn't start inside the floor. - On landing,
move_and_slide()setvelocity.yto 0 for you. It removes the part of the velocity that points into the surface it hit, so the body doesn't build up downward speed while standing. - Movement and gravity are in
_physics_process, which runs at a fixed rate (60 times per second by default). Moving physics bodies in_processmakes collisions depend on the frame rate.
In a real project you can read the gravity from the project settings and any gravity-changing areas with get_gravity() (Godot 4.3+), as the built-in template does: velocity += get_gravity() * delta. It returns zero until the body has been through its first physics step, which is one reason the examples here use a constant.
Sliding along walls
"Slide" means that when the body hits a surface, the leftover motion continues along it. Fly diagonally into a wall and the horizontal part stops while the vertical part keeps going. After the call, get_slide_collision_count() and get_slide_collision(i) tell you what was hit:
extends Node2D
# frames: 4
var player: CharacterBody2D
func make_box(size: Vector2) -> CollisionShape2D:
var shape := RectangleShape2D.new()
shape.size = size
var cs := CollisionShape2D.new()
cs.shape = shape
return cs
func _ready():
var wall := StaticBody2D.new()
wall.name = "Wall"
wall.add_child(make_box(Vector2(20, 400)))
wall.position = Vector2(30, 0) # left face at x = 20
add_child(wall)
player = CharacterBody2D.new()
player.add_child(make_box(Vector2(16, 16)))
add_child(player)
player.velocity = Vector2(300, -120) # up and to the right, into the wall
func _physics_process(_delta):
player.move_and_slide()
print("pos ", player.position.snappedf(0.01), " vel ", player.velocity.snappedf(0.01), " on_wall=", player.is_on_wall())
for i in player.get_slide_collision_count():
var hit := player.get_slide_collision(i)
print(" hit ", hit.get_collider().name, " normal ", hit.get_normal())pos (5.0, -2.0) vel (300.0, -120.0) on_wall=false
pos (10.0, -4.0) vel (300.0, -120.0) on_wall=false
pos (11.93, -6.0) vel (0.0, -120.0) on_wall=true
hit Wall normal (-1.0, 0.0)
hit Wall normal (-1.0, 0.0)
pos (11.93, -8.0) vel (0.0, -120.0) on_wall=true
hit Wall normal (-1.0, 0.0)
move_and_slide() can collide several times in one call (up to max_slides, 4 by default): on the third frame it hit the wall, slid, and touched it again. The normal points out of the surface, so (-1, 0) is a wall to the right. Whether a surface counts as floor, wall or ceiling depends on the angle between its normal and up_direction (default Vector2.UP); anything within floor_max_angle (45° by default) is floor.
move_and_collide: you decide the response
move_and_collide(motion) is the lower-level call. It moves by exactly the vector you pass (so you multiply by delta), stops at the first contact and returns a KinematicCollision2D, or null if nothing was hit. Nothing is slid or zeroed, so it suits balls, projectiles and anything that bounces:
extends Node2D
# frames: 60
var ball: CharacterBody2D
var velocity := Vector2(240, 180)
func make_box(size: Vector2) -> CollisionShape2D:
var shape := RectangleShape2D.new()
shape.size = size
var cs := CollisionShape2D.new()
cs.shape = shape
return cs
func add_wall(pos: Vector2, size: Vector2):
var w := StaticBody2D.new()
w.position = pos
w.add_child(make_box(size))
add_child(w)
func _ready():
add_wall(Vector2(0, 60), Vector2(200, 10)) # floor, top at y = 55
add_wall(Vector2(60, 0), Vector2(10, 200)) # right wall, left face at x = 55
ball = CharacterBody2D.new()
ball.add_child(make_box(Vector2(10, 10)))
add_child(ball)
func _physics_process(delta):
var hit := ball.move_and_collide(velocity * delta)
if hit:
velocity = velocity.bounce(hit.get_normal())
print("frame ", Engine.get_physics_frames(), ": bounced off normal ", hit.get_normal(), " -> velocity ", velocity)frame 13: bounced off normal (-1.0, 0.0) -> velocity (-240.0, 180.0)
frame 18: bounced off normal (0.0, -1.0) -> velocity (-240.0, -180.0)
Here velocity is a script variable, not the body's property, because move_and_collide ignores the property. Vector2.bounce(normal) reflects the vector off the surface. The next lesson, Platformer Movement with Input, adds running and jumping to move_and_slide.
Test yourself
A CharacterBody2D falls onto a floor using move_and_slide(). What happens to velocity.y on the frame it lands?
- It keeps growing because gravity is still added
move_and_slide()sets it to 0 because the motion points into the floor- It reverses and the body bounces
- It becomes
NaN
What is the difference between move_and_slide() and move_and_collide()?
move_and_slide()uses thevelocityproperty and handles sliding and floor detection;move_and_collide()moves by a motion vector you pass and returns the first collision- They are identical
move_and_collide()only works for RigidBody2Dmove_and_slide()must be multiplied by delta,move_and_collide()must not
Which node should you use for a player that must respond precisely to input and collide with walls?
- RigidBody2D
- StaticBody2D
- CharacterBody2D
- Area2D