🛠️ Real-World Patterns
Production-ready code patterns for common game systems
🏃 Player Movement
Platformer Controller
Complete 2D platformer with gravity, jumping, and coyote time.
extends CharacterBody2D
@export var speed := 300.0
@export var jump_force := -400.0
@export var coyote_time := 0.15
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var coyote_timer := 0.0
var was_on_floor := false
func _physics_process(delta: float) -> void:
# Gravity
velocity.y += gravity * delta
# Coyote time (late jump)
if is_on_floor():
coyote_timer = coyote_time
else:
coyote_timer -= delta
# Jump
if Input.is_action_just_pressed("jump") and coyote_timer > 0:
velocity.y = jump_force
coyote_timer = 0
# Horizontal movement
var direction := Input.get_axis("move_left", "move_right")
velocity.x = direction * speed
move_and_slide()Top-Down 8-Direction
Smooth 8-directional movement for top-down games.
extends CharacterBody2D
@export var speed := 200.0
@export var acceleration := 800.0
@export var friction := 1000.0
func _physics_process(delta: float) -> void:
var input_dir := Input.get_vector(
"move_left", "move_right",
"move_up", "move_down"
)
if input_dir != Vector2.ZERO:
# Accelerate towards input direction
velocity = velocity.move_toward(
input_dir * speed,
acceleration * delta
)
# Rotate sprite to face movement
$Sprite2D.rotation = input_dir.angle()
else:
# Apply friction when no input
velocity = velocity.move_toward(
Vector2.ZERO,
friction * delta
)
move_and_slide()