Using overlaps to detect entities¶
Overlaps can be used to determine whether any entity with a collider exists in a given area. A sphere, box, capsule, or circular sector with a central angle of 180 degrees is an example of such an area. In this tutorial, you will learn to use GeometrySector180 to detect if any entity with a collider exists within such a sector.
Prerequisite¶
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 sector to detect entities¶
To detect entities within a certain area using a sector with a central angle of 180 degrees:
-
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 Asset Box>Models.
-
Activate the model by simply clicking + Feature and closing the Add Feature window right away. An entity ID will be automatically assigned to the active model.
-
-
Create an empty object ("OverlapSample") 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. OverlapSample determines the starting point and direction of the sector.
-
Add the following script to OverlapSample to simulate sector casting. For more information on how to add a script, see Creating or adding scripts.
-- Get the position and rotation of OverlapSample local cmp = script:GetYaComponent("YaMovableComponent") local pos = cmp:GetPosition() local rot = cmp:GetRotationQuaternion() local queryInstance = YaQueryParameter.Instance() local queryParam = queryInstance:QueryAllPhysicsLayer() -- Create a sector with a central angle of 180 degrees, the radius of 2 meters, and the height of 1 meter queryParam = queryParam:GeometrySector180(2, 1) -- Set the sector in the forward direction of OverlapSample queryParam = queryParam:GeometryDirection(rot * float3.New(0, 0, 1)) local overLapEntities = PhysicsAPI.Overlap(pos, queryParam) -- Return the ID of all entities that the sector hits. If no entity is hit, return sector overlap nil. if overLapEntities ~= nil then for k, v in pairs(overLapEntities:ToTable()) do print(v.EntityId) end else print("sector overlap nil") end
In this example, we are casting a sector from the position of OverlapSample in the forward direction. If the sector hits any entities, their entity IDs will be returned. If the sector hits nothing, sector overlap nil will be returned.
-
Save the script and playtest it in Play Mode. Click the Console button to check what is hit by the sector.