1. What We're Building
This tutorial walks through a complete roll-a-ball game in Godot 4: you steer a marble with the keyboard, roll it across platforms, up a ramp and over a narrow bridge, and collect every gem as fast as you can. It is the classic “roll a ball” starter project, done the Godot 4 way with RigidBody3D physics.
Everything below comes from a real, working project (Godot 4.6, Forward+ renderer). The code excerpts are copied from its scripts, not written for the article. You will learn:
- How to control a
RigidBody3Dball with forces and torque so it actually rolls instead of sliding. - A simple ground check using contact monitoring, a jump impulse, a speed cap and a respawn when the ball falls off.
- A smooth third-person follow camera that trails the ball.
- Spinning, bobbing gems built on
Area3Dthat pop when collected. - A HUD with a gem counter, a timer and a win message.
- A course made only from box meshes, plus the environment settings that keep a bright, toy-like look from washing out.
The project has just four scripts: ball.gd, camera_rig.gd, gem.gd and main.gd, plus two scenes, main.tscn and gem.tscn.
2. Scene Setup and Input Actions
The main scene is a Node3D called Main with main.gd attached. Its children are:
Main (Node3D, main.gd)
├─ WorldEnvironment
├─ Sun (DirectionalLight3D, shadows on)
├─ Course (Node3D)
│ ├─ Start, Runway, Ramp, Plateau, Bridge, Goal (StaticBody3D)
│ │ └─ Mesh (MeshInstance3D) + Collision (CollisionShape3D)
│ ├─ GoalRing (MeshInstance3D, TorusMesh)
│ └─ GoalWall (StaticBody3D)
├─ Ball (RigidBody3D, ball.gd)
│ ├─ Mesh (SphereMesh), Stripe (CylinderMesh)
│ └─ Collision (SphereShape3D)
├─ CameraRig (Node3D, camera_rig.gd)
│ └─ Camera3D
├─ Gems (Node3D)
│ └─ Gem1 … Gem14 (instances of gem.tscn)
└─ HUD (CanvasLayer)
└─ GemLabel, TimeLabel, Message (Label)
Next, open Project → Project Settings → Input Map and add six actions. The project binds both WASD and the arrow keys for movement:
| Action | Keys |
|---|---|
move_forward | W, Up |
move_back | S, Down |
move_left | A, Left |
move_right | D, Right |
jump | Space |
restart | R |
3. The RigidBody3D Ball
For a marble game, RigidBody3D is the right body type. You want the physics engine to handle rolling down ramps, bouncing and carrying momentum; you only nudge the ball with forces. (A CharacterBody3D would make you fake all of that by hand.)
In the scene, the Ball node sits slightly above the start platform and has a few physics properties set in the Inspector: a PhysicsMaterial override with bounce = 0.25, linear_damp = 0.3 so it slowly coasts to a stop, and angular_damp = 1.5 so it doesn't spin forever. Its children are a SphereMesh, a thin CylinderMesh “stripe” (without it, a plain-colored sphere looks like it is sliding even when it rolls) and a SphereShape3D collision shape.
Exports and setup
extends RigidBody3D
## Player ball: rolls with WASD/arrows, jumps with Space, respawns when it falls.
signal fell
@export var roll_force := 22.0
@export var air_force := 8.0
@export var jump_impulse := 6.5
@export var max_speed := 11.0
@export var fall_limit := -12.0
var spawn_point := Vector3.ZERO
var _on_ground := false
func _ready() -> void:
spawn_point = global_position
contact_monitor = true
max_contacts_reported = 4
All the tuning values are @exported, so you can tweak them in the Inspector while you playtest. Two lines in _ready() matter a lot: a RigidBody3D does not report what it touches unless you turn on contact_monitor and set max_contacts_reported above zero. Without them, get_colliding_bodies() always returns an empty array and the ground check below never succeeds.
Rolling with force and torque
func _physics_process(_delta: float) -> void:
var input := Input.get_vector("move_left", "move_right", "move_forward", "move_back")
var dir := Vector3(input.x, 0.0, input.y)
_on_ground = _check_ground()
if dir != Vector3.ZERO:
var flat_speed := Vector2(linear_velocity.x, linear_velocity.z).length()
if flat_speed < max_speed:
apply_central_force(dir * (roll_force if _on_ground else air_force))
# Spin the ball visibly in the rolling direction.
apply_torque(Vector3(dir.z, 0.0, -dir.x) * 4.0)
Step by step:
Input.get_vector()turns the four actions into aVector2with length up to 1. Its Y axis is negative for “forward”, which maps neatly onto Godot's 3D convention where forward is-Z. The camera looks down-Ztoo, so “up” on the keyboard rolls the ball away from the camera.apply_central_force()pushes the ball through its center. On the ground it usesroll_force; in the air it uses the weakerair_force, which gives a little air control without letting you fly.- Max speed: the force is only applied while the horizontal speed (X and Z, ignoring falling speed) is below
max_speed. That caps acceleration from input while still letting gravity and ramps do their thing. - Visible rolling: a central force alone mostly slides the ball until friction catches up.
apply_torque()around the axis perpendicular to the movement direction,Vector3(dir.z, 0, -dir.x), spins it the right way immediately. Pressing forward (dir.z = -1) gives a torque around-X, which rolls the ball toward-Z.
Jumping and respawning
if Input.is_action_just_pressed("jump") and _on_ground:
apply_central_impulse(Vector3.UP * jump_impulse)
if global_position.y < fall_limit:
respawn()
fell.emit()
func _check_ground() -> bool:
for body in get_colliding_bodies():
if body is StaticBody3D:
return true
return false
func respawn() -> void:
linear_velocity = Vector3.ZERO
angular_velocity = Vector3.ZERO
global_position = spawn_point
- Jump:
apply_central_impulse()is a one-off kick, the right tool for a jump (a force would have to be applied over several frames). It only fires while_on_groundis true, so no double jumps. - Ground check: since every piece of the course is a
StaticBody3D, “touching any static body” is a good enough definition of grounded for this game. It also counts walls, which is fine here. If you add vertical walls you can climb, compare contact normals or use aRayCast3Dpointing down instead. - Respawn: once the ball drops below
fall_limit(-12), it is reset to the position it started at, with all velocity cleared, and thefellsignal tells the rest of the game. Settingglobal_positiondirectly works fine for a simple respawn like this. For heavier teleport logic on a rigid body, Godot's docs recommend doing it in_integrate_forces().
4. A Smooth Follow Camera
Parenting the camera to the ball would be a disaster: a rolling ball rotates, so the camera would spin with it. Instead the camera lives in a separate CameraRig (Node3D) with a Camera3D child (FOV 65). The rig follows the ball's position only, and the camera re-aims at the ball every physics frame.
extends Node3D
## Smooth follow camera that trails the ball from behind and above.
@export var target_path: NodePath
@export var offset := Vector3(0, 5.5, 8.5)
@export var smoothing := 5.0
@onready var _target: Node3D = get_node_or_null(target_path)
@onready var _cam: Camera3D = $Camera3D
In the scene, target_path is set to ../Ball. The offset puts the camera 5.5 units up and 8.5 units behind (positive Z, since the course runs toward -Z).
func snap() -> void:
if _target:
global_position = _target.global_position + offset
_cam.look_at(_target.global_position + Vector3(0, 0.5, 0), Vector3.UP)
func _physics_process(delta: float) -> void:
if not _target:
return
var goal := _target.global_position + offset
global_position = global_position.lerp(goal, clampf(smoothing * delta, 0.0, 1.0))
_cam.look_at(_target.global_position + Vector3(0, 0.5, 0), Vector3.UP)
- Smoothing:
lerp()moves the rig a fraction of the way toward the goal each frame.smoothing * deltakeeps that fraction roughly frame-rate independent, andclampf()stops it from overshooting on a long frame. - Look-at target: the camera aims half a unit above the ball's center, which frames the course ahead slightly better than aiming dead center.
- Why
_physics_process? The ball moves in physics ticks, so following it in the same tick avoids jitter between the two. snap()jumps the camera straight to its target position. It exists because of a real bug: after the ball fell off and respawned, the smoothed camera was left far away and took a while to drift back, losing the ball. Nowmain.gdcallssnap()on every respawn.
5. Collectible Gems with Area3D
Each gem is its own scene, gem.tscn: an Area3D root with gem.gd, a low-poly SphereMesh (6 radial segments and 2 rings, which gives a faceted, crystal-like shape) with a glowing cyan emissive material, and a SphereShape3D collision shape (radius 0.6) that is a bit larger than the mesh so pickups feel generous. Fourteen instances are placed along the course under the Gems node.
extends Area3D
## Collectible gem: spins and bobs, pops when the ball touches it.
signal collected
@export var spin_speed := 2.5
@export var bob_height := 0.18
var _base_y := 0.0
var _time := 0.0
var _taken := false
func _ready() -> void:
add_to_group("gems")
_base_y = position.y
_time = randf() * TAU
body_entered.connect(_on_body_entered)
func _process(delta: float) -> void:
_time += delta
rotate_y(spin_speed * delta)
if not _taken:
position.y = _base_y + sin(_time * 3.0) * bob_height
Each gem adds itself to the "gems" group so main.gd can count them without a hard-coded list. Starting _time at a random phase (randf() * TAU) means the gems don't all bob in lockstep, a cheap trick that makes the scene feel more alive.
func _on_body_entered(body: Node3D) -> void:
if _taken or not body is RigidBody3D:
return
_taken = true
collected.emit()
var tw := create_tween().set_parallel(true)
tw.tween_property(self, "scale", Vector3.ONE * 1.8, 0.12).set_trans(Tween.TRANS_BACK)
tw.tween_property(self, "position:y", position.y + 1.2, 0.3)
tw.chain().tween_property(self, "scale", Vector3.ONE * 0.01, 0.15)
tw.chain().tween_callback(queue_free)
The _taken flag guarantees a gem is only counted once, even if body_entered fires again during the pop animation. The ball is the only RigidBody3D in the scene, so the type check is all the filtering needed. The tween runs in parallel at first: the gem swells to 1.8x with a springy TRANS_BACK curve while floating up, then chain() switches back to sequential steps to shrink it away and call queue_free.
6. HUD: Gem Counter, Timer and Win
The HUD is a CanvasLayer with three Labels: GemLabel and TimeLabel in the top-left corner, and a centered Message label for prompts. Big font sizes plus thick purple and pink outlines (outline_size 12 and 16) keep the text readable over the bright course. main.gd ties everything together:
func _ready() -> void:
for gem in get_tree().get_nodes_in_group("gems"):
total += 1
gem.collected.connect(_on_gem_collected)
ball.fell.connect(_on_ball_fell)
_update_hud()
_flash("Collect all the gems!", 2.0)
func _process(delta: float) -> void:
if not finished:
elapsed += delta
time_label.text = "TIME %.1f" % elapsed
if Input.is_action_just_pressed("restart"):
get_tree().reload_current_scene()
Child nodes are ready before their parent, so by the time Main._ready() runs, every gem has already joined the "gems" group. The timer simply accumulates delta until the run is finished, and R reloads the whole scene for a fresh attempt.
func _on_gem_collected() -> void:
got += 1
_update_hud()
var tw := create_tween()
gem_label.pivot_offset = gem_label.size / 2.0
tw.tween_property(gem_label, "scale", Vector2.ONE * 1.35, 0.08)
tw.tween_property(gem_label, "scale", Vector2.ONE, 0.15)
if got >= total:
finished = true
_flash("ALL GEMS! %.1f s - press R to replay" % elapsed, 0.0)
func _on_ball_fell() -> void:
$CameraRig.snap()
if not finished:
_flash("Oops! Try again", 1.2)
Every pickup gives the counter a quick “punch” by scaling it to 1.35x and back. Setting pivot_offset to the label's center first makes it grow from the middle instead of the top-left corner. Collecting the last gem stops the timer and shows the final time. _flash() sets the message text and, when given a duration above zero, fades it out with tween_interval() followed by a modulate:a tween; a duration of 0.0 keeps the win message on screen.
7. Building the Course from Primitive Meshes
No imported models are needed. Every course piece is a StaticBody3D with a MeshInstance3D using a BoxMesh and a CollisionShape3D using a BoxShape3D of exactly the same size. Matching the two is the whole trick: if the visual box and the collision box differ, the ball will float above or sink into the floor.
The course runs along the -Z axis:
- Start: an 8 × 10 pink platform where the ball spawns.
- Runway: a 6 × 14 yellow strip with gems on alternating sides.
- Ramp: a 6 × 8.3 orange slab rotated about 14° around the X axis, leading up to the next level.
- Plateau: an 8 × 10 mint platform, two units higher than the start.
- Bridge: a narrow 2.2-unit-wide purple strip, the main place to fall off.
- Goal: a 10 × 10 blue platform with a glowing yellow
TorusMeshring standing upright as the finish marker. - GoalWall: a low wall at the far end. It was added after playtesting showed the ball could roll straight off the end of the goal.
Each platform gets its own StandardMaterial3D in a saturated candy color with roughness = 0.6 and a little rim lighting, which brightens the edges and helps the blocks read clearly against the sky. A DirectionalLight3D named Sun, angled down at the course with shadows enabled, grounds the ball visually so you can judge jumps.
The gems hover about 0.8 units above the platform surface (a little higher on the ramp). With the ball's radius of 0.5 and the gem's 0.6 collision radius, the ball touches them just by rolling through, with no jump required.
8. Making the Colors Pop
Bright, saturated albedo colors are not enough on their own. With realistic lighting and tonemapping, candy colors can come out pale and washed out, and that is exactly what happened during this build. The fix lives entirely in the WorldEnvironment's Environment resource. These are the final values from the project:
| Property | Value | Why |
|---|---|---|
background_mode | Sky, ProceduralSkyMaterial | Blue top, pink horizon, purple ground colors for a cheerful backdrop. |
ambient_light_source | Color, lavender, energy 0.55 | Tints shadows a soft purple instead of gray. |
tonemap_mode | Filmic, exposure 0.95 | Handles bright highlights gracefully; slightly lower exposure keeps colors from blowing out. |
ssao_enabled | true | Contact shadows where blocks meet, adding depth. |
glow_enabled | true, intensity 0.5, HDR threshold 1.2 | Only very bright pixels glow: the emissive gems and goal ring. |
adjustment_enabled | contrast 1.1, saturation 1.35 | Pushes the colors back up after tonemapping. |
The combination is what works: a tonemapper and slightly reduced exposure tame the highlights, glow with a high threshold makes emissive objects shine without fogging the whole screen, and the color adjustment brings back the saturation that tonemapping takes away. The gems use emission_energy_multiplier = 1.6 (1.5 on the goal ring) so they cross the glow threshold and visibly sparkle.
This project uses the Forward+ renderer. If you target the Compatibility renderer (for example for web exports), check which Environment effects it supports in your Godot version, since features such as SSAO are not available there.
9. Building It with AI
Everything in this tutorial was built by Claude Code through Godot MCP Pro from a single prompt, in about 3.5 minutes of AI work. Here is the prompt, word for word:
Godot MCP Pro connects the AI to the live Godot editor, so it does not just write scripts. It creates the nodes, meshes and materials, sets up input actions, runs the game, simulates key presses and takes screenshots to see what actually happened. That playtesting loop is how it caught bugs you would normally only find by playing:
- Washed-out colors. The first version looked pale. It retuned tonemapping, glow and saturation into the settings shown in section 8.
- The camera lost the ball after a fall. It added
snap()to the camera rig and called it on respawn. - The ball could roll off the end. It added the
GoalWallbehind the goal. - An engine warning from the gem pop animation. It caught the warning while testing and fixed it.
See the full build on the 3D Ball Roller showcase page, or watch the build video. The prompt says “core basics first” for a reason: from here you can keep prompting to add moving platforms, checkpoints, more levels or a best-time leaderboard, and the AI tests each change the same way.
10. FAQ
Should a ball rolling game in Godot 4 use RigidBody3D or CharacterBody3D?
Use RigidBody3D. A marble should be pushed by physics, roll down ramps, bounce and keep momentum, which the physics engine does for you. You steer it with apply_central_force(), apply_torque() and apply_central_impulse() instead of setting its velocity every frame.
Why does my RigidBody3D ball slide instead of rolling?
apply_central_force() pushes through the center, so on its own the ball mostly translates. Add apply_torque() around the axis perpendicular to the movement direction (Vector3(dir.z, 0, -dir.x)) so it spins visibly, and give the mesh a stripe or texture so the rotation is easy to see.
How do I check if a RigidBody3D is on the ground in Godot 4?
Enable contact_monitor, set max_contacts_reported above zero, then loop over get_colliding_bodies() and treat any StaticBody3D contact as ground. Only allow the jump impulse while that check is true.
Can AI build a Godot ball rolling game?
Yes. This one was built from one prompt by Claude Code using Godot MCP Pro in about 3.5 minutes. Because the AI could run the game, simulate input and take screenshots, it found and fixed its own bugs, such as washed-out colors and the camera losing the ball after a fall.
Build Your Next Godot Game with AI
Godot MCP Pro gives AI assistants like Claude Code 190 tools inside the live Godot 4 editor: build 3D scenes, set up physics and materials, run the game, simulate input and read errors — all from chat.
add_mesh_instance
setup_physics_body
setup_environment
play_scene
get_game_screenshot
One-time purchase · Lifetime updates · See pricing details