सामग्री पर जाएँ

लेसन 20 · 2D Games

Player Movement with CharacterBody2D

Move a 2D character in Godot 4 with CharacterBody2D, move_and_slide, gravity, jumping, acceleration, coyote time and jump buffering, with runnable Python stand-ins.

Player movement is where a game starts to feel good or bad. Godot 4 gives you CharacterBody2D, a physics body that you move with your own code. You decide the velocity; the engine moves the body, stops it at walls and slides it along floors and slopes. This is different from a RigidBody2D, which the physics engine moves for you.

The real GDScript is shown read-only. The Godot engine cannot run on this site, so every runnable block is a Python stand-in: it models the arithmetic the engine and your script perform, so you can experiment with the numbers. Before this lesson, see sprites and tilemaps.

The basic script

A CharacterBody2D has a built-in velocity property (a Vector2, in pixels per second). Your job each physics frame is to change velocity, then call move_and_slide().

GDSCRIPT
extends CharacterBody2D

const SPEED := 220.0
const JUMP_VELOCITY := -420.0   # negative y is UP in 2D
var gravity: float = ProjectSettings.get_setting("physics/2d/default_gravity")

func _physics_process(delta: float) -> void:
	if not is_on_floor():
		velocity.y += gravity * delta

	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	var direction := Input.get_axis("move_left", "move_right")
	velocity.x = direction * SPEED

	move_and_slide()

Four things to notice:

  • Movement code lives in _physics_process(delta), which runs at a fixed rate (60 times per second by default). _process runs once per rendered frame, and its rate varies.
  • The y axis points down, so a jump is a negative velocity and gravity is a positive one.
  • Input.get_axis() returns -1, 0 or 1 (or an analog value on a gamepad) from two Input Map actions you define in Project Settings.
  • move_and_slide() uses velocity and the engine's own delta, so you do not multiply by delta yourself.
Python Stand-in (Python, not Godot): gravity and a jump, frame by frame

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The peak is about v² / (2g) = 420² / 1960, close to 90 pixels. When you want a specific jump height h, solve backward: JUMP_VELOCITY = -sqrt(2 * gravity * h).

Acceleration, friction and "game feel"

Setting velocity.x = direction * SPEED is instant: the character starts and stops at full speed. Most games blend toward the target instead. move_toward(from, to, step) does this without overshoot:

GDSCRIPT
const ACCELERATION := 1600.0
const FRICTION := 2000.0

var direction := Input.get_axis("move_left", "move_right")
if direction != 0.0:
	velocity.x = move_toward(velocity.x, direction * SPEED, ACCELERATION * delta)
else:
	velocity.x = move_toward(velocity.x, 0.0, FRICTION * delta)
Python Stand-in (Python, not Godot): move_toward gives smooth starts and stops

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Coyote time and jump buffering

Two tricks make platformers forgiving, and players love them:

  • Coyote time: allow a jump for a short moment (about 0.1 s) after walking off a ledge.
  • Jump buffering: remember a jump press made slightly (about 0.1 s) before landing, and perform it on landing.
GDSCRIPT
const COYOTE_TIME := 0.1
const BUFFER_TIME := 0.1
var coyote := 0.0
var buffered := 0.0

func _physics_process(delta: float) -> void:
	coyote = COYOTE_TIME if is_on_floor() else maxf(coyote - delta, 0.0)
	buffered = BUFFER_TIME if Input.is_action_just_pressed("jump") else maxf(buffered - delta, 0.0)

	if buffered > 0.0 and coyote > 0.0:
		velocity.y = JUMP_VELOCITY
		buffered = 0.0
		coyote = 0.0
	# ... gravity and horizontal movement as before
Python Stand-in (Python, not Godot): does the jump fire?

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first press is forgiven (it falls inside the 0.1 s window, 6 frames); the second is too late and returns None.

move_and_slide and the floor

move_and_slide() tells you what it hit afterwards. is_on_floor(), is_on_wall() and is_on_ceiling() depend on up_direction (default Vector2.UP) and floor_max_angle (about 45 degrees). For a top-down game set motion_mode = MOTION_MODE_FLOATING so there is no floor and no gravity. get_slide_collision_count() and get_slide_collision(i) return what the body touched, useful for stomping enemies. See collisions, layers and areas for how bodies detect each other.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Where should movement code for a CharacterBody2D normally go?

    _physics_process runs at a fixed rate in step with the physics engine; move_and_slide() belongs there.
  2. 2. Which value makes a character jump upward in 2D?

    In Godot 2D the y axis grows downward, so up is negative.
  3. 3. What does coyote time allow?

    A short grace timer, reset while on the floor, keeps the jump allowed for a moment after leaving the ground.
  4. 4. Do you multiply velocity by delta before calling move_and_slide()?

    move_and_slide() already uses the physics step. You do multiply acceleration terms such as gravity * delta when you change velocity.

Summary

  • CharacterBody2D is moved by your code: change velocity, call move_and_slide() in _physics_process.
  • Up is negative y; gravity adds to velocity.y while not on the floor.
  • move_toward() gives acceleration and friction; coyote time and jump buffering make jumps forgiving.
  • For top-down games use floating motion mode and no gravity.

Next: Collisions, Layers and Areas in 2D

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।