In Lesson 3, we attached a script to the Sprite2D character and moved it left and right with ← →. In this lesson, you'll define your own controls and rebuild the character as a "body that can stand on a floor." When you're done, the character will drop onto the floor, land, and walk with either the arrow keys or A D. Jumping comes in the next lesson.
Finished project for Lesson 4: project-lesson04.zip (6 KB)
We'll pick up where Lesson 3 left off. If you get lost along the way, extract this zip, open it with "Import" in the Project Manager, and compare.
Why switch to CharacterBody2D?
Right now the character is a Sprite2D, a node that only displays an image. Changing position moves it, but as far as Godot is concerned it's just a picture, so it can't stand on a floor or stop at a wall. If you wanted it to stand on a floor, you'd have to write code like "don't go below this y position" yourself, and that gets painful every time you add another floor or platform.
Instead, we'll let Godot's physics engine handle collisions. The nodes used for 2D physics come in a few kinds, each with its own job.
| Node | What it does | Where we use it in this game |
|---|---|---|
StaticBody2D | An object that doesn't move. Other objects collide with it | The floor (this lesson) |
CharacterBody2D | An object you move with code. It stops or slides when it hits something | The player (this lesson) |
RigidBody2D | An object the physics engine moves. It rolls and bounces | (Not used) |
Area2D | A region that doesn't collide, but tells you when something overlaps it | Coins and enemies (Lesson 6) |
CharacterBody2D is a perfect fit for a player character. It lets you split the work: your code decides how it moves ("go right when the right key is pressed"), and the physics engine handles collisions ("don't sink into the floor," "stop at walls"). For more on CharacterBody2D, see The complete guide to CharacterBody2D/3D in Godot 4.
Define your controls with the InputMap
In Lesson 3, we used ui_left and ui_right, which come built into Godot. Those names are really meant for navigating menus. In a game, the usual approach is to define your own "actions." An action is a name for a control, like "move left" or "jump," and you choose which keys trigger it in the InputMap.
- Open Project → Project Settings... from the menu and select the Input Map tab at the top.
- Type
move_leftin the Add New Action field and click Add to its right. Amove_leftrow appears in the list. - Click the "+" button (Add Event) at the right end of that row. The Event Configuration dialog opens. Press ← on your keyboard, then click OK.
- Click "+" again, and this time register A. Now
move_leftresponds to either ← or A. - In the same way, create
move_right(→ and D) andjump(Space). We'll usejumpin the next lesson. - Close the dialog. The settings are saved to
project.godotautomatically.
| Action name | Keys |
|---|---|
move_left | ←, A |
move_right | →, D |
jump | Space |
Your code only asks "is move_left pressed?" The InputMap takes care of which keys that means, so if you later want to change keys or add gamepad support, you won't have to change a single line of code.
Action names are used as-is, as strings, in your code. If you mistype move_right as move_rigth, it won't work (see Common pitfalls).
Build the player scene
Just like we did with the coin, we'll put the player in its own scene, player.tscn. The root is a CharacterBody2D, and its children give it a "look" and a "collision shape."
Player (CharacterBody2D)
├─ Sprite2D … the look (icon.svg)
└─ CollisionShape2D … the collision shape (a rectangle)- Choose Scene → New Scene from the menu.
- Under Create Root Node: in the Scene dock, click Other Node, type
CharacterBody2Din the search box, and create it. Rename it toPlayer(double-click to rename). - Right-click
Player→ Add Child Node... and add aSprite2D. Dragicon.svgfrom the FileSystem dock onto Texture in the Inspector, and set Transform → Scale to0.5,0.5. The 128 × 128 pixels we used through Lesson 3 is too big for hopping around on platforms, so we shrink it to 64 × 64. - Use "Add Child Node..." on
Playeragain to add aCollisionShape2D. Click "<empty>" next to Shape in the Inspector and choose New RectangleShape2D. - Click the
RectangleShape2Dnow in Shape to expand it, and set Size to56,56. Making it slightly smaller than the image keeps the corners from catching on things. - Press Ctrl + S and save it as
res://player.tscn.
Before you added the CollisionShape2D, you probably saw a yellow ⚠ icon next to Player. It's a warning that says "this has no collision shape, so it can't collide with anything." It goes away once you set a shape.
Rewrite player.gd
The player.gd from Lesson 3 says extends Sprite2D, so you can't attach it to a CharacterBody2D as is. We'll rewrite it first, then attach it again.
- Double-click
player.gdin the FileSystem dock to open it, delete everything, replace it with the code below, and save. - Go back to the
player.tscntab and dragplayer.gdfrom the FileSystem dock ontoPlayerin the Scene dock. If a scroll icon appears next toPlayer, the script is attached.
extends CharacterBody2D
# Left/right movement speed (pixels per second)
@export var speed: float = 300.0
# Gravity strength: the downward speed increases by this much every second
@export var gravity: float = 1200.0
# Called on every physics step (60 times per second by default)
func _physics_process(delta: float) -> void:
# When not standing on the floor, increase the downward speed a little at a time (this is gravity)
if not is_on_floor():
velocity.y += gravity * delta
# -1 for left, 1 for right, 0 if neither is pressed
var direction: float = Input.get_axis("move_left", "move_right")
velocity.x = direction * speed
# Move according to velocity. If we hit a floor or wall, stop there
move_and_slide()
# Keep x between the left and right edges so we stay on screen
var screen_width: float = get_viewport_rect().size.x
position.x = clamp(position.x, 32.0, screen_width - 32.0)We removed make_greeting, which printed the greeting, since its job is done. Let's go through the new parts one at a time.
_physics_process
The _process from Lesson 3 was called "every time the screen is drawn." _physics_process is called on every physics step, at a fixed interval (60 times per second by default). Code that moves things together with the physics engine belongs here. delta means the same thing as before: the number of seconds since the last call.
velocity and move_and_slide()
velocity is a variable CharacterBody2D has built in. It's a Vector2 that means "how far to move in x and y per second." In Lesson 3 we changed position directly, but this time we set the velocity and let move_and_slide() do the moving.
move_and_slide() moves the body according to velocity, stops it if it hits a floor or wall along the way, and slides it along slopes. It also multiplies by delta for you, which is why velocity.x = direction * speed doesn't multiply by delta.
Gravity and is_on_floor()
In Godot's 2D, y gets bigger as you go down. velocity.y += gravity * delta means "increase the downward speed by 1200 every second," and that's gravity. The longer something falls, the faster it goes, so the fall looks natural.
is_on_floor() returns true if the body touched a floor during the last move_and_slide(). While the character is standing on the floor we don't add gravity, so the speed doesn't keep growing forever.
Input.get_axis()
In Lesson 3, we wrote two if statements to build direction. Input.get_axis("move_left", "move_right") does that in one line. It returns -1 if only left is pressed, 1 if only right is pressed, and 0 if both or neither are pressed.
Keeping the character on screen
The last two lines are the same as in Lesson 3: they keep the character from leaving the screen. The character is now 64 wide, so the distance from the edge is 32. Once we build a stage wider than the screen, with walls, in the next lesson, we won't need this anymore.
Make a floor and place the player
Go back to main.tscn and build a floor. The floor doesn't move, so we use a StaticBody2D. Physics nodes have no look of their own, so we give it a colored rectangle (ColorRect) as a child to make it visible.
- Right-click
Main→ "Add Child Node..." to add aStaticBody2D, and name itFloor. In the Inspector, set Transform → Position to576,608. - Add a
ColorRectas a child ofFloor. In the Inspector, under Layout → Transform, set Position to-576,-40and Size to1152,80, and set Color to any green you like. - Add a
CollisionShape2Das a child ofFloor, set its Shape to "New RectangleShape2D," and set Size to1152,80. - Select the old
Player(the Sprite2D from Lesson 3) and press Delete to remove it. - Click the chain-link icon at the top of the Scene dock (Instantiate Child Scene...) and choose
player.tscn. Set the newPlayer's Position to576,400. We place it a bit above the floor so we can watch it fall. - Save with Ctrl + S.
Here's what the finished main.tscn tree looks like:
Main (Node2D)
├─ Title (Label)
├─ Floor (StaticBody2D)
│ ├─ ColorRect
│ └─ CollisionShape2D
├─ Player (player.tscn)
├─ Coin (coin.tscn)
├─ Coin2 (coin.tscn)
└─ Coin3 (coin.tscn)
A CollisionShape2D rectangle is placed with its center at the parent's position. A ColorRect, on the other hand, is placed with its top-left corner at its Position. To line up the look and the collision exactly, we shift the ColorRect up and to the left by half its width (576) and half its height (40).
Run it and check
Press F5 to run. If the character falls from above, stops on the floor, and walks left and right with both ← → and A D, you've got it.
If you want to see the collision shapes, check Debug → Visible Collision Shapes in the menu before running. The player and floor will show their collision shapes overlaid in light blue. It's handy for figuring out why things aren't colliding the way you expect.
- Open
player.tscnand set Gravity to300inPlayer's Inspector. It falls slowly, like on the moon. - Set the y of Player's Position to
100and drop it from higher up. - Duplicate
Floorwith Ctrl + D to make a small step (don't forget to resize both the ColorRect and the collision shape).
Common pitfalls
| Symptom | Cause and fix |
|---|---|
| The character falls right through the floor | Either Player's or Floor's CollisionShape2D has no Shape set, or Floor's collision doesn't line up with its look. Check with "Visible Collision Shapes." |
The Output panel shows The InputMap action "move_rigth" doesn't exist. Did you mean "move_right"? | The action name in your code is misspelled. Godot 4.6 suggests a close match with "Did you mean." Make it exactly the same as the name in the InputMap. |
| Pressing keys does nothing (no errors) | The action may not have any keys registered in the InputMap. In the "Input Map" tab, check that keys are listed under each action. |
| You get an error when attaching the script | Line 1 of player.gd still says extends Sprite2D. Change it to extends CharacterBody2D, save, and then attach it. |
| The character slowly sinks or jitters while standing on the floor | You might be moving it in _process. Code that moves things with physics goes in _physics_process. |
Working with AI
This lesson is half "editor setup" and half "code," and AI's strengths and weaknesses split cleanly along that line.
- A (chat): it can write code like
player.gdwith hardly any problems. But you have to set up the InputMap and create the nodes yourself in the editor. If you ask "which menu do I click," you may get steps from older versions mixed in, so compare against this lesson. - B (Claude Code, etc.): it can write
player.gdand.tscnfiles directly. It can write the InputMap intoproject.godot, but if the file is changed from outside while the editor is open, the editor may overwrite it and wipe the changes. To be safe, close the editor before asking. - C (+ MCP): with Godot MCP Pro, the AI can register the InputMap actions (
set_input_action), add the CharacterBody2D and CollisionShape2D (add_node,add_resource), and create and swap scripts (create_script,attach_script), all inside the open editor. You can also leave it to run the game (play_scene), press the → key (simulate_action), and read the player's position andis_on_floorstate (get_game_node_properties) to check.
Whichever approach you use, you still play it yourself at the end to check how it feels. You can't settle on the "just right" gravity or speed by looking at numbers alone.
Recap and what's next
- Define controls as actions in the InputMap, and use only the action names in your code
- Use
CharacterBody2Dfor a character that collides, andStaticBody2Dfor a floor that doesn't move - Give physics nodes a collision shape with
CollisionShape2D - Put physics code in
_physics_process: setvelocity, then move withmove_and_slide() - Gravity is just adding a little to
velocity.yevery step.is_on_floor()tells you whether you're on the floor - Debug → Visible Collision Shapes lets you see the collision shapes
Next time, it's finally time to jump. We'll also replace the ColorRect floor with a tilemap, build a stage wider than the screen, and have a camera follow the player.
Want AI to handle the editor work too?
With Godot MCP Pro, Claude Code or Cursor can add nodes, register InputMap actions, and even run the game and press keys to check, all inside your open editor (190 tools, $15 one-time purchase). You can finish this series without MCP.
Learn more about Godot MCP Pro · The complete guide to CharacterBody2D/3D