Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Трассировка лучей

Введение

Одна из самых частых задач в разработке игр — это испускание луча (или собственного объекта с формой) и проверка того, что он пересекает. Это позволяет создавать сложные поведения, ИИ и т.д. В этом учебном пособии объясняется, как это сделать в 2D и 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.

Во многих случаях, однако, трассировка лучей требует более сложной обработки так что должен существовать способ делать это через код.

Пространство

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.

Доступ к пространству

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.

Используйте следующий код в 2D:

func _physics_process(delta):
    var space_rid = get_world_2d().space
    var space_state = PhysicsServer2D.space_get_direct_state(space_rid)

Или более прямо:

func _physics_process(delta):
    var space_state = get_world_2d().direct_space_state

И для 3D:

func _physics_process(delta):
    var space_state = get_world_3d().direct_space_state

Запрос трассировки лучей

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

func _physics_process(delta):
    var space_state = get_world_2d().direct_space_state
    # use global coordinates, not local to node
    var query = PhysicsRayQueryParameters2D.create(Vector2(0, 0), Vector2(50, 100))
    var result = space_state.intersect_ray(query)

Результатом будет словарь. Если луч ни с чем не столкнулся, словарь будет пуст. Если же столкнулся, то будет содержать информацию о столкновении:

if result:
    print("Hit at point: ", result.position)

Словарь result после столкновения будет содержать следующие данные:

{
   position: Vector2 # point in world space for collision
   normal: Vector2 # normal in world space for collision
   collider: Object # Object collided or null (if unassociated)
   collider_id: ObjectID # Object it collided against
   rid: RID # RID it collided against
   shape: int # shape index of collider
   metadata: Variant() # metadata of collider
}

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.

const RAY_LENGTH = 1000

func _physics_process(delta):
    var space_state = get_world_3d().direct_space_state
    var cam = $Camera3D
    var mousepos = get_viewport().get_mouse_position()

    var origin = cam.project_ray_origin(mousepos)
    var end = origin + cam.project_ray_normal(mousepos) * RAY_LENGTH
    var query = PhysicsRayQueryParameters3D.create(origin, end)
    query.collide_with_areas = true

    var result = space_state.intersect_ray(query)

Исключения столкновений

Распространенный способ использования трассировки лучей это сбор данных об окружающем мире для персонажа. Одна из проблем с этим возникает когда у персонажа есть коллайдер, и луч будет сталкиваться с ним, как показано на следующем рисунке:

../../_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:

extends CharacterBody2D

func _physics_process(delta):
    var space_state = get_world_2d().direct_space_state
    var query = PhysicsRayQueryParameters2D.create(global_position, player_position)
    query.exclude = [self]
    var result = space_state.intersect_ray(query)

Массивы исключений могут содержать объекты или RIDs.

Маска столкновения

Метод исключений хорошо работает, когда нужно исключить родительское тело, но очень неудобен, если это нужно сделать для больших и/или динамических списков исключений. Для этого случая гораздо эффективнее использовать систему слоев/масок столкновений.

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:

extends CharacterBody2D

func _physics_process(delta):
    var space_state = get_world_2d().direct_space_state
    var query = PhysicsRayQueryParameters2D.create(global_position, target_position,
        collision_mask, [self])
    var result = space_state.intersect_ray(query)

См. Пример кода для получения дополнительной информации о том, как установить маску столкновений.

Трассировка лучей из экрана в 3D

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

Для его получения с помощью камеры можно использовать следующий код:

const RAY_LENGTH = 1000.0

func _input(event):
    if event is InputEventMouseButton and event.pressed and event.button_index == 1:
          var camera3d = $Camera3D
          var from = camera3d.project_ray_origin(event.position)
          var to = from + camera3d.project_ray_normal(event.position) * RAY_LENGTH

Помните, что во время выполнения _input() пространство может быть заблокировано, поэтому на практике этот запрос должен выполняться в _physics_process().