Ray-casting

Introduction

One of the most common tasks in game development is casting a ray (or custom shaped object) and checking what it hits. This enables complex behaviors, AI, etc. to take place. This tutorial will explain how to do this in 2D and 3D.

Godot stores all the low level game information in servers, while the scene is only a frontend. As such, ray casting is generally a lower-level task. For simple raycasts, nodes like RayCast3D and RayCast2D will work, as they return every frame what the result of a raycast is.

Many times, though, ray-casting needs to be a more interactive process so a way to do this by code must exist.

Space

In the physics world, Godot stores all the low level collision and physics information in a space. The current 2d space (for 2D Physics) can be obtained by accessing CanvasItem.get_world_2d().space. For 3D, it’s Node3D.get_world_3d().space.

The resulting space RID can be used in PhysicsServer3D and PhysicsServer2D respectively for 3D and 2D.

Accessing space

Godot physics runs by default in the same thread as game logic, but may be set to run on a separate thread to work more efficiently. Due to this, the only time accessing space is safe is during the Node._physics_process() callback. Accessing it from outside this function may result in an error due to space being locked.

To perform queries into physics space, the PhysicsDirectSpaceState2D and PhysicsDirectSpaceState3D must be used.

Use the following code in 2D:

GDScriptC#

  1. func _physics_process(delta):
  2. var space_rid = get_world_2d().space
  3. var space_state = PhysicsServer2D.space_get_direct_state(space_rid)
  1. public override void _PhysicsProcess(double delta)
  2. {
  3. var spaceRid = GetWorld2D().Space;
  4. var spaceState = PhysicsServer2D.SpaceGetDirectState(spaceRid);
  5. }

Or more directly:

GDScriptC#

  1. func _physics_process(delta):
  2. var space_state = get_world_2d().direct_space_state
  1. public override void _PhysicsProcess(double delta)
  2. {
  3. var spaceState = GetWorld2D().DirectSpaceState;
  4. }

And in 3D:

GDScriptC#

  1. func _physics_process(delta):
  2. var space_state = get_world_3d().direct_space_state
  1. public override void _PhysicsProcess(double delta)
  2. {
  3. var spaceState = GetWorld3D().DirectSpaceState;
  4. }

Raycast query

For performing a 2D raycast query, the method PhysicsDirectSpaceState2D.intersect_ray() may be used. For example:

GDScriptC#

  1. func _physics_process(delta):
  2. var space_state = get_world_2d().direct_space_state
  3. # use global coordinates, not local to node
  4. var query = PhysicsRayQueryParameters2D.create(Vector2(0, 0), Vector2(50, 100))
  5. var result = space_state.intersect_ray(query)
  1. public override void _PhysicsProcess(double delta)
  2. {
  3. var spaceState = GetWorld2D().DirectSpaceState;
  4. // use global coordinates, not local to node
  5. var query = PhysicsRayQueryParameters2D.Create(Vector2.Zero, new Vector2(50, 100));
  6. var result = spaceState.IntersectRay(query);
  7. }

The result is a dictionary. If the ray didn’t hit anything, the dictionary will be empty. If it did hit something, it will contain collision information:

GDScriptC#

  1. if result:
  2. print("Hit at point: ", result.position)
  1. if (result.Count > 0)
  2. GD.Print("Hit at point: ", result["position"]);

The result dictionary when a collision occurs contains the following data:

  1. {
  2. position: Vector2 # point in world space for collision
  3. normal: Vector2 # normal in world space for collision
  4. collider: Object # Object collided or null (if unassociated)
  5. collider_id: ObjectID # Object it collided against
  6. rid: RID # RID it collided against
  7. shape: int # shape index of collider
  8. metadata: Variant() # metadata of collider
  9. }

The data is similar in 3D space, using Vector3 coordinates. Note that to enable collisions with Area3D, the boolean parameter collide_with_areas must be set to true.

GDScript

  1. const RAY_LENGTH = 1000
  2. func _physics_process(delta):
  3. var space_state = get_world_3d().direct_space_state
  4. var cam = $Camera3D
  5. var mousepos = get_viewport().get_mouse_position()
  6. var origin = cam.project_ray_origin(mousepos)
  7. var end = origin + cam.project_ray_normal(mousepos) * RAY_LENGTH
  8. var query = PhysicsRayQueryParameters3D.create(origin, end)
  9. query.collide_with_areas = true
  10. var result = space_state.intersect_ray(query)

Collision exceptions

A common use case for ray casting is to enable a character to gather data about the world around it. One problem with this is that the same character has a collider, so the ray will only detect its parent’s collider, as shown in the following image:

../../_images/raycast_falsepositive.webp

To avoid self-intersection, the intersect_ray() parameters object can take an array of exceptions via its exclude property. This is an example of how to use it from a CharacterBody2D or any other collision object node:

GDScriptC#

  1. extends CharacterBody2D
  2. func _physics_process(delta):
  3. var space_state = get_world_2d().direct_space_state
  4. var query = PhysicsRayQueryParameters2D.create(global_position, player_position)
  5. query.exclude = [self]
  6. var result = space_state.intersect_ray(query)
  1. using Godot;
  2. public partial class MyCharacterBody2D : CharacterBody2D
  3. {
  4. public override void _PhysicsProcess(double delta)
  5. {
  6. var spaceState = GetWorld2D().DirectSpaceState;
  7. var query = PhysicsRayQueryParameters2D.Create(globalPosition, playerPosition);
  8. query.Exclude = new Godot.Collections.Array<Rid> { GetRid() };
  9. var result = spaceState.IntersectRay(query);
  10. }
  11. }

The exceptions array can contain objects or RIDs.

Collision Mask

While the exceptions method works fine for excluding the parent body, it becomes very inconvenient if you need a large and/or dynamic list of exceptions. In this case, it is much more efficient to use the collision layer/mask system.

The intersect_ray() parameters object can also be supplied a collision mask. For example, to use the same mask as the parent body, use the collision_mask member variable. The array of exceptions can be supplied as the last argument as well:

GDScriptC#

  1. extends CharacterBody2D
  2. func _physics_process(delta):
  3. var space_state = get_world_2d().direct_space_state
  4. var query = PhysicsRayQueryParameters2D.create(global_position, target_position,
  5. collision_mask, [self])
  6. var result = space_state.intersect_ray(query)
  1. using Godot;
  2. public partial class MyCharacterBody2D : CharacterBody2D
  3. {
  4. public override void _PhysicsProcess(double delta)
  5. {
  6. var spaceState = GetWorld2D().DirectSpaceState;
  7. var query = PhysicsRayQueryParameters2D.Create(globalPosition, targetPosition,
  8. CollisionMask, new Godot.Collections.Array<Rid> { GetRid() });
  9. var result = spaceState.IntersectRay(query);
  10. }
  11. }

See Code example for details on how to set the collision mask.

3D ray casting from screen

Casting a ray from screen to 3D physics space is useful for object picking. There is not much need to do this because CollisionObject3D has an “input_event” signal that will let you know when it was clicked, but in case there is any desire to do it manually, here’s how.

To cast a ray from the screen, you need a Camera3D node. A Camera3D can be in two projection modes: perspective and orthogonal. Because of this, both the ray origin and direction must be obtained. This is because origin changes in orthogonal mode, while normal changes in perspective mode:

../../_images/raycast_projection.png

To obtain it using a camera, the following code can be used:

GDScriptC#

  1. const RAY_LENGTH = 1000.0
  2. func _input(event):
  3. if event is InputEventMouseButton and event.pressed and event.button_index == 1:
  4. var camera3d = $Camera3D
  5. var from = camera3d.project_ray_origin(event.position)
  6. var to = from + camera3d.project_ray_normal(event.position) * RAY_LENGTH
  1. private const float RayLength = 1000.0f;
  2. public override void _Input(InputEvent @event)
  3. {
  4. if (@event is InputEventMouseButton eventMouseButton && eventMouseButton.Pressed && eventMouseButton.ButtonIndex == MouseButton.Left)
  5. {
  6. var camera3D = GetNode<Camera3D>("Camera3D");
  7. var from = camera3D.ProjectRayOrigin(eventMouseButton.Position);
  8. var to = from + camera3D.ProjectRayNormal(eventMouseButton.Position) * RayLength;
  9. }
  10. }

Remember that during _input(), the space may be locked, so in practice this query should be run in _physics_process().


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next