TExcelTAD
Home › Godot 4 with GDScript › Areas, Collision Layers & Raycasts

Areas, Collision Layers & Raycasts

Bodies collide. Most game logic, though, only needs to know that something is there: the player touched a coin, an enemy is in sight range, the floor ends in front of a patrolling slime. Godot has two tools for that: areas report overlaps through signals, and raycasts answer "what is along this line?". Both are filtered by collision layers and masks.

Layers and masks

Every physics object (bodies and areas) has two sets of 32 bits:

  • collision_layer: the layers this object is on.
  • collision_mask: the layers this object looks at (collides with, or detects).

A detects B when A's mask contains one of B's layers. The two directions are independent: a coin's mask can include the player's layer while the player's mask ignores coins. Name the layers once, then pick them by name in the Inspector:

  1. Open Project > Project Settings > General > Layer Names > 2D Physics.
  2. Name layer 1 world, layer 2 player, layer 3 enemies, layer 4 pickups.
  3. Select a node, open Collision in the Inspector and click the squares for Layer and Mask. Hovering a square shows its name.

In code, use set_collision_layer_value(n, true) and set_collision_mask_value(n, true) with layer numbers 1–32. The collision_layer property itself is a bit field: layer n is the value 1 << (n - 1), so layer 2 alone is 2, layer 4 alone is 8.

Area2D: pickups and triggers

An Area2D with a shape emits body_entered(body) and body_exited(body) for physics bodies, and area_entered(area) / area_exited(area) for other areas, whenever something its mask can see starts or stops overlapping it. Below, three coins look only for layer 2. The player (layer 2) and a slime (layer 3) fly through the coins' row; the third coin sits in the slime's path:

gdscript · try it yourself
extends Node2D

# frames: 30
# Layer plan: 1 = world, 2 = player, 3 = enemies, 4 = pickups
var player: CharacterBody2D
var slime: CharacterBody2D
var coins := 0

func make_box(size: Vector2) -> CollisionShape2D:
	var shape := RectangleShape2D.new()
	shape.size = size
	var cs := CollisionShape2D.new()
	cs.shape = shape
	return cs

func make_body(body_name: String, layer: int, pos: Vector2) -> CharacterBody2D:
	var body := CharacterBody2D.new()
	body.name = body_name
	body.collision_layer = 0
	body.set_collision_layer_value(layer, true)
	body.collision_mask = 0                    # collides with nothing; it only flies past
	body.add_child(make_box(Vector2(8, 8)))
	body.position = pos
	add_child(body)
	return body

func _ready():
	player = make_body("Player", 2, Vector2(0, 0))
	slime = make_body("Slime", 3, Vector2(0, 20))
	for i in 3:
		var coin := Area2D.new()
		coin.name = "Coin%d" % i
		coin.collision_layer = 0
		coin.set_collision_layer_value(4, true)
		coin.collision_mask = 0
		coin.set_collision_mask_value(2, true)  # coins only look for the player
		coin.add_child(make_box(Vector2(6, 6)))
		coin.position = Vector2(30 + i * 40, 0 if i < 2 else 20)
		coin.body_entered.connect(_on_coin_body_entered.bind(coin))
		add_child(coin)
	print("player layer bits: ", player.collision_layer, ", coin mask bits: ", get_node("Coin0").collision_mask)

func _on_coin_body_entered(body: Node2D, coin: Area2D):
	coins += 1
	print("frame ", Engine.get_physics_frames(), ": ", body.name, " collected ", coin.name, " (coins: ", coins, ")")
	coin.queue_free()

func _physics_process(delta):
	player.position.x += 300 * delta
	slime.position.x += 300 * delta
player layer bits: 2, coin mask bits: 2
frame 7: Player collected Coin0 (coins: 1)
frame 15: Player collected Coin1 (coins: 2)

Coin2 never fires: the slime overlaps it, but the slime is on layer 3 and the coin's mask only has layer 2. That one setting replaces an if body.is_in_group("player") check in every pickup script.

Notes:

  • .bind(coin) appends an extra argument to the signal's arguments, so one handler serves every coin. In a real game each coin is an instanced coin.tscn with its own script and connects to its own signal.
  • Overlap signals are emitted during the physics step. If the handler changes physics state (disabling a shape, adding a body), do it with set_deferred("disabled", true) or call_deferred(...); Godot reports an error when you flush queries mid-step. queue_free() is already deferred.
  • monitoring (does this area detect others?) and monitorable (can others detect it?) turn an area off without removing it.
  • get_overlapping_bodies() and get_overlapping_areas() return the current list, updated once per physics frame.

The coin scene in the editor:

text
Coin (Area2D)                  layer: pickups, mask: player
├── AnimatedSprite2D
└── CollisionShape2D           CircleShape2D

Then select Coin, open the Node dock, double-click body_entered and press Connect. Godot adds func _on_body_entered(body: Node2D) -> void: to the script.

Raycasts from code

PhysicsDirectSpaceState2D.intersect_ray() casts a ray right now and returns a dictionary describing the first hit (collider, position, normal, rid, shape, ...) or an empty dictionary. Get the space from get_world_2d().direct_space_state, and only query it inside _physics_process, when the physics state is consistent:

gdscript · try it yourself
extends Node2D

# frames: 1
func make_box(size: Vector2) -> CollisionShape2D:
	var shape := RectangleShape2D.new()
	shape.size = size
	var cs := CollisionShape2D.new()
	cs.shape = shape
	return cs

func add_static(body_name: String, pos: Vector2, size: Vector2, layer: int):
	var body := StaticBody2D.new()
	body.name = body_name
	body.position = pos
	body.collision_layer = 0
	body.set_collision_layer_value(layer, true)
	body.add_child(make_box(size))
	add_child(body)

func _ready():
	add_static("Crate", Vector2(50, 0), Vector2(10, 10), 3)     # layer 3
	add_static("Wall", Vector2(100, 0), Vector2(10, 100), 1)    # layer 1

func _physics_process(_delta):
	var space := get_world_2d().direct_space_state
	var query := PhysicsRayQueryParameters2D.create(Vector2.ZERO, Vector2(200, 0))
	var hit := space.intersect_ray(query)
	print("all layers: ", hit.collider.name, " at ", hit.position, " normal ", hit.normal)

	query.collision_mask = 1                  # only layer 1
	hit = space.intersect_ray(query)
	print("mask 1:     ", hit.collider.name, " at ", hit.position)

	query.to = Vector2(0, 200)                # straight down: nothing there
	hit = space.intersect_ray(query)
	print("downwards:  ", hit, " empty=", hit.is_empty())
all layers: Crate at (45.0, 0.0) normal (-1.0, 0.0)
mask 1:     Wall at (95.0, 0.0)
downwards:  {  } empty=true

Line-of-sight checks, hitscan weapons and "what did I click?" are all one intersect_ray. A ray starting inside a body ignores it by default (hit_from_inside = false); add your own body to query.exclude ([get_rid()]) when casting from inside a character. Rays don't hit areas unless collide_with_areas is true.

RayCast2D: a ray that lives in the scene

For a ray you check every frame from the same place (ground checks, ledge detection, "is the player in front of me?"), add a RayCast2D node. It updates once per physics frame and you read is_colliding(), get_collider() and get_collision_point(). Here a patrolling enemy turns around at the platform edge when its ray stops touching ground:

gdscript · try it yourself
extends Node2D

# frames: 40
var enemy: CharacterBody2D
var ledge_ray: RayCast2D
var dir := 1.0

func make_box(size: Vector2) -> CollisionShape2D:
	var shape := RectangleShape2D.new()
	shape.size = size
	var cs := CollisionShape2D.new()
	cs.shape = shape
	return cs

func _ready():
	var platform := StaticBody2D.new()
	platform.add_child(make_box(Vector2(60, 10)))   # x from -30 to 30, top at y = 8
	platform.position = Vector2(0, 13)
	add_child(platform)
	enemy = CharacterBody2D.new()
	enemy.add_child(make_box(Vector2(8, 8)))
	enemy.position = Vector2(0, 3.92)
	add_child(enemy)
	ledge_ray = RayCast2D.new()
	ledge_ray.position = Vector2(6, 0)        # just ahead of the enemy's feet
	ledge_ray.target_position = Vector2(0, 10)
	enemy.add_child(ledge_ray)
	ledge_ray.force_raycast_update()
	print("ground ahead at start: ", ledge_ray.is_colliding())

func _physics_process(delta):
	if not ledge_ray.is_colliding():
		dir = -dir
		ledge_ray.position.x = 6 * dir
		print("frame ", Engine.get_physics_frames(), ": no ground ahead at x = ", snappedf(enemy.position.x, 0.1), ", turning")
	enemy.velocity = Vector2(120 * dir, 0)
	enemy.move_and_slide()
ground ahead at start: true
frame 14: no ground ahead at x = 26.0, turning
frame 40: no ground ahead at x = -26.0, turning

A new RayCast2D has not been updated yet, so is_colliding() is false until the first physics step. Without the force_raycast_update() call in _ready, this enemy would "see a ledge" on frame 1 and turn around at once. Call force_raycast_update() whenever you move a ray and need the answer in the same frame. target_position is relative to the ray node, and the ray ignores its parent body by default (exclude_parent).

Test yourself

A coin Area2D has mask = layer 2 only. A slime on layer 3 walks through it. Does body_entered fire?

  1. Yes, areas detect everything
  2. No, the coin's mask does not include layer 3
  3. Only if the slime's mask includes layer 4
  4. Only for RigidBody2D

What is the collision_layer value of a node that is only on layer 4?

  1. 4
  2. 8
  3. 16
  4. 3

Why did the enemy example call force_raycast_update() in _ready?

  1. RayCast2D nodes are disabled by default
  2. A RayCast2D only updates during physics steps, so before the first step it reports no collision
  3. It is required for every node with a script
  4. To make the ray hit areas