Using raycasting to detect entities¶
Raycasting offers a method for detecting entities by sending invisible rays from a specified position and in a specified direction. In this tutorial, you can use the RaycastSingle function to detect entities with a ray and return the first entity that the ray intersects with.
Visual Studio Code is installed and integrated with your Studio. If you haven't done this already, follow the instructions in How to start coding to download and integrate.
Casting a ray to detect entities¶
You can cast a ray and use RaycastSingle to detect entities and return the first entity that the ray hits. Here's how:
Add a target to detect.
Make sure the target has a collider attached to it. In our example, we add model Transverse_Roadblocks which has a mesh collider, to the scene by selecting it via Scenery>Models>Basics.
Make the model active by simply clicking + Component and closing the Add Components window right away. An entity ID will be automatically assigned to the active model.
Create an empty object ("RaycastSample") by clicking Empty Object in the Explorer window and use the Move Gizmo to adjust its position, making sure its Z-axis directed towards the target. RaycastSample determines the starting point and direction of the ray.
Add the following script to RaycastSample to simulate raycasting. For more information on how to add a script, see Creating or adding scripts.
local queryInstance = YaQueryParameter.Instance() local queryParam = queryInstance:QueryAllPhysicsLayer() -- Get the starting point and direction of RaycastSample local cmp = script:GetYaComponent("YaMovableComponent") local pos = cmp:GetPosition() local rot = cmp:GetRotationQuaternion() -- Set the direction for raycasting local entityForward = rot * float3.New(0, 0, 1) local queryResult = PhysicsAPI.RaycastSingle(pos, entityForward, queryParam) -- Return the Entity ID of the first entity that the ray hits, and the distance, position, and normal of the contact point print("ray hit entity: " .. tostring(queryResult.Entity.EntityId)) print("ray distance: " .. tostring(queryResult.Distance)) print("ray hit point:" .. tostring(queryResult.Position)) print("ray hit normal:" .. tostring(queryResult.Normal))
In this example, we are sending out a ray from the position of RaycastSample in the forward direction. If any entity is hit, the hit variable to return contains information about the first entity that has been hit, including its entity ID, and the distance, position, and normal of the contact point. If no entity is hit, all parameters will return 0 or [0,0,0] except for the ray distance (close to 0).
Save the script and enter Play Mode to playtest it. Click the Console button to get detailed information about how a ray hits Transverse_Roadblocks.