Make Games with Godot 4 and AI · Lesson 4 of 11

Godot 4 Movement: InputMap & CharacterBody2D (Lesson 4)

You'll define your own controls in the InputMap and rebuild the character as a body that can stand on a floor (CharacterBody2D). It will fall with gravity, land on the floor, and walk with the arrow keys or A and D.

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.

NodeWhat it doesWhere we use it in this game
StaticBody2DAn object that doesn't move. Other objects collide with itThe floor (this lesson)
CharacterBody2DAn object you move with code. It stops or slides when it hits somethingThe player (this lesson)
RigidBody2DAn object the physics engine moves. It rolls and bounces(Not used)
Area2DA region that doesn't collide, but tells you when something overlaps itCoins 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.

  1. Open Project → Project Settings... from the menu and select the Input Map tab at the top.
  2. Type move_left in the Add New Action field and click Add to its right. A move_left row appears in the list.
  3. Click the "+" button (Add Event) at the right end of that row. The Event Configuration dialog opens. Press ← on your keyboard, then click OK.
  4. Click "+" again, and this time register A. Now move_left responds to either ← or A.
  5. In the same way, create move_right (→ and D) and jump (Space). We'll use jump in the next lesson.
  6. Close the dialog. The settings are saved to project.godot automatically.
Action nameKeys
move_left←, A
move_right→, D
jumpSpace

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.

Use plain letters for action names, and watch the spelling

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.tscn structure
Player (CharacterBody2D)
├─ Sprite2D           … the look (icon.svg)
└─ CollisionShape2D   … the collision shape (a rectangle)
  1. Choose Scene → New Scene from the menu.
  2. Under Create Root Node: in the Scene dock, click Other Node, type CharacterBody2D in the search box, and create it. Rename it to Player (double-click to rename).
  3. Right-click Player → Add Child Node... and add a Sprite2D. Drag icon.svg from the FileSystem dock onto Texture in the Inspector, and set Transform → Scale to 0.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.
  4. Use "Add Child Node..." on Player again to add a CollisionShape2D. Click "<empty>" next to Shape in the Inspector and choose New RectangleShape2D.
  5. Click the RectangleShape2D now in Shape to expand it, and set Size to 56, 56. Making it slightly smaller than the image keeps the corners from catching on things.
  6. Press Ctrl + S and save it as res://player.tscn.
player.tscn open in the Godot editor. The Scene dock lists Player, Sprite2D, and CollisionShape2D, and the Inspector shows Speed and Gravity
The finished player.tscn. The Inspector on the right shows the script's @export variables (Speed and Gravity) along with the CharacterBody2D settings

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.

  1. Double-click player.gd in the FileSystem dock to open it, delete everything, replace it with the code below, and save.
  2. Go back to the player.tscn tab and drag player.gd from the FileSystem dock onto Player in the Scene dock. If a scroll icon appears next to Player, the script is attached.
player.gd
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.

  1. Right-click Main → "Add Child Node..." to add a StaticBody2D, and name it Floor. In the Inspector, set Transform → Position to 576, 608.
  2. Add a ColorRect as a child of Floor. In the Inspector, under Layout → Transform, set Position to -576, -40 and Size to 1152, 80, and set Color to any green you like.
  3. Add a CollisionShape2D as a child of Floor, set its Shape to "New RectangleShape2D," and set Size to 1152, 80.
  4. Select the old Player (the Sprite2D from Lesson 3) and press Delete to remove it.
  5. Click the chain-link icon at the top of the Scene dock (Instantiate Child Scene...) and choose player.tscn. Set the new Player's Position to 576, 400. We place it a bit above the floor so we can watch it fall.
  6. Save with Ctrl + S.

Here's what the finished main.tscn tree looks like:

main.tscn structure
Main (Node2D)
├─ Title (Label)
├─ Floor (StaticBody2D)
│   ├─ ColorRect
│   └─ CollisionShape2D
├─ Player (player.tscn)
├─ Coin (coin.tscn)
├─ Coin2 (coin.tscn)
└─ Coin3 (coin.tscn)
main.tscn open with Floor selected. A wide green floor runs along the bottom, the player is in the middle, and three coins are above
Floor (StaticBody2D) selected. Its Position is (576, 608). The ColorRect and CollisionShape2D extend the same distance up, down, left, and right from the center of Floor
Why the ColorRect's Position is negative

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.

The running game. The character stands on a green floor, with three coins floating in the air
The character lands on the floor and can now walk left and right

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.

Try it
  • Open player.tscn and set Gravity to 300 in Player's Inspector. It falls slowly, like on the moon.
  • Set the y of Player's Position to 100 and drop it from higher up.
  • Duplicate Floor with Ctrl + D to make a small step (don't forget to resize both the ColorRect and the collision shape).

Common pitfalls

SymptomCause and fix
The character falls right through the floorEither 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 scriptLine 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 floorYou might be moving it in _process. Code that moves things with physics goes in _physics_process.

Working with AI

If you hand this lesson's work to AI

This lesson is half "editor setup" and half "code," and AI's strengths and weaknesses split cleanly along that line.

I'm making a 2D action game in Godot 4.6. Write a player.gd for a CharacterBody2D player that moves left and right with the InputMap actions move_left / move_right and stands on the floor using gravity. Make speed and gravity @export variables. Also explain, for a beginner, how velocity and move_and_slide relate.
Read project.godot and check whether move_left (← and A), move_right (→ and D), and jump (Space) are registered correctly in the InputMap. If anything is missing, tell me what to do in the editor to fix it.
  • A (chat): it can write code like player.gd with 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.gd and .tscn files directly. It can write the InputMap into project.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 and is_on_floor state (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 CharacterBody2D for a character that collides, and StaticBody2D for a floor that doesn't move
  • Give physics nodes a collision shape with CollisionShape2D
  • Put physics code in _physics_process: set velocity, then move with move_and_slide()
  • Gravity is just adding a little to velocity.y every 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

All lessons in the series (11)
  1. Lesson 1: Installing Godot and setting up AI tools
  2. Lesson 2: Nodes and scenes
  3. Lesson 3: GDScript basics
  4. Lesson 4: Input and player movementYou are here
  5. Lesson 5: Gravity, jumping, and tilemaps
  6. Lesson 6: Signals, coins, and enemies
  7. Lesson 7: UI and screen transitions
  8. Lesson 8: Sound and game feel
  9. Lesson 9: Letting AI playtest your game
  10. Lesson 10: Exporting and publishing
  11. Lesson 11: Bonus: one-prompt games by genre