Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท 2D Games

Collisions, Layers and Areas in 2D

Understand Godot 4 2D physics bodies, collision shapes, layers and masks, Area2D triggers, RayCast2D and signals, with Python stand-ins for the bitmask and overlap tests.

A game is mostly things touching other things: the player hits a wall, a bullet hits an enemy, a coin overlaps the player. Godot solves this with collision objects that own shapes. This lesson covers the body types, how layers and masks decide who collides with whom, and how Area2D detects overlaps without blocking.

Godot code is read-only here because the engine cannot run on this site. Runnable blocks are Python stand-ins that model the underlying maths. For moving a body see player movement.

The collision node family

All of these extend CollisionObject2D. Each needs at least one child CollisionShape2D (or CollisionPolygon2D) with a shape resource, or it has no physical size. A yellow warning triangle in the scene tree tells you when the shape is missing.

Node Moved by Typical use
StaticBody2D Nobody Walls, floors, platforms
CharacterBody2D Your code Player, enemies
RigidBody2D The physics engine Crates, balls, debris
AnimatableBody2D Animation or code Moving platforms
Area2D Nobody (detects only) Pickups, hitboxes, trigger zones

Prefer simple shapes (circle, rectangle, capsule) over polygons: they are faster and more stable. A capsule is the best shape for a character because it slides over small steps.

Layers and masks

Every collision object has two sets of 32 on/off bits:

  • Layer: "which layers am I on?" (what I am).
  • Mask: "which layers do I scan?" (what I look for).

Object A reacts to object B when A's mask shares a bit with B's layer. It is one-directional: a player can detect coins while coins ignore the player. Name your layers in Project Settings > Layer Names > 2D Physics (for example 1 world, 2 player, 3 enemy, 4 player bullet, 5 pickup) and tick checkboxes in the Inspector. In code, use set_collision_layer_value(2, true) and set_collision_mask_value(1, true), where the number is the 1-based layer.

Python Stand-in (Python, not Godot): who detects whom, with bitmasks

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.

Read the table: the player sees coins, but coins see nothing, yet the overlap is still reported to the player. Bullets pass the player because the bullet mask does not include the player layer.

Area2D: detect, don't block

An Area2D has a shape but never stops anything. It emits signals when bodies or other areas enter or leave:

GDSCRIPT
extends Area2D   # attached to a Coin scene

signal collected(value: int)
@export var value := 10

func _ready() -> void:
	body_entered.connect(_on_body_entered)

func _on_body_entered(body: Node2D) -> void:
	if body.is_in_group("player"):
		collected.emit(value)
		queue_free()

Use body_entered / body_exited for physics bodies and area_entered / area_exited for other areas. get_overlapping_bodies() gives a list right now. A classic pattern is a hitbox (an Area2D on the attack) and a hurtbox (an Area2D on the character that can be damaged). Signals are explained in Nodes and Signals (see the track page).

Do not change collision shapes or disable them directly inside a physics callback such as body_entered. Use set_deferred("disabled", true) on the shape so the change happens after the physics step; otherwise Godot prints an error.

What a collision test really does

Under the hood, the engine first checks cheap bounding boxes, then exact shapes. For two axis-aligned rectangles the test is just four comparisons.

Python Stand-in (Python, not Godot): rectangle overlap and penetration depth

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.

move_and_slide() does something similar for you: it finds the collision, removes the penetration, and slides the leftover motion along the surface.

RayCast2D and queries

A RayCast2D casts a line from its origin along target_position. Call is_colliding() and get_collider() to see the first hit. Use it for ground checks, line-of-sight and ledge detection. For one-off queries from code, use the physics server:

GDSCRIPT
func can_see(target: Node2D) -> bool:
	var space := get_world_2d().direct_space_state
	var query := PhysicsRayQueryParameters2D.create(global_position, target.global_position)
	query.exclude = [self]
	query.collision_mask = 1   # only walls block sight
	return space.intersect_ray(query).is_empty()

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Object A has mask layer 3 and object B is on layer 3. What happens?

    Detection is one-directional: A reacts to B when A's mask contains B's layer.
  2. 2. Which node detects overlaps but never blocks movement?

    Area2D is for triggers: it emits signals but has no solid collision response.
  3. 3. Why use set_deferred("disabled", true) on a CollisionShape2D inside body_entered?

    Changing physics state during the physics callback is not allowed; set_deferred waits for a safe moment.
  4. 4. Which shape is a good default for a platformer character?

    Capsules are cheap and slide smoothly over small bumps.

Summary

  • Collision objects need shapes; choose the body type by who moves it.
  • Layers say what an object is; masks say what it scans for. Detection is one-directional.
  • Area2D detects with signals and never blocks.
  • Defer physics changes made from physics callbacks.
  • RayCast2D and intersect_ray answer "what is in that direction?".

Next: Camera and Parallax in 2D