By using Raycasts game scripts can detect various geometry intersections. For instance, you can perform various overlap tests and raycasts to scan the space around the player. Probably the most common case is to use raycast to place a third-person camera right behind the player but without clipping the scene objects.
Flax provides various C# API for raycasting and geometry tests:
- Physics.RayCast
- Physics.RayCastAll
- Physics.BoxCast
- Physics.BoxCastAll
- Physics.SphereCast
- Physics.SphereCastAll
- Physics.CheckBox
- Physics.CheckSphere
- Physics.OverlapBox
- Physics.OverlapSphere
Additionally you can perform similar tests for single collider using Collider.RayCast and Collider.ClosestPoint methods.
This code sends a raycast from the object location and draws a red sphere at the hit location.
public override void OnUpdate()
{
RayCastHit hit;
if (Physics.RayCast(Actor.Position, Actor.Direction, out hit))
{
DebugDraw.DrawSphere(new BoundingSphere(hit.Point, 50), Color.Red);
}
}
Frequently you want a raycast to start from the player's position, however, such a raycast will instantly detect the player's collider. The correct way of solving this is to use the layers feature.
To do so, assign a different layer to the player and colliders. You can also assign different layers to different groups of colliders.
Then, in the raycast function, set the layerMask
accordingly. The layer mask uses one bit for each layer. For example, to only check collisions with colliders from layer 3, you would typically use 1 << 3
as the layer mask.
public override void OnUpdate()
{
// Collision with all layers, except layer 1
if (Physics.RayCast(Actor.Position, Actor.Direction, out RayCastHit hit, layerMask: ~(1U << 1)))
{
DebugDraw.DrawSphere(new BoundingSphere(hit.Point, 50), Color.Red);
}
}