Skip to main content

Querying

Sometimes, you want to find the nearest collider to a point, or find all colliders in an area. For this, you can use querying.

Querying searches all colliders in the physics engine for the ones that meet certain conditions:

warning

Querying is performed on colliders not bodies. That means if a body has multiple colliders, it will be returned multiple times in the results. If this is an issue for you, consider putting the main collider in one category, and then all auxiliary colliders in another category, then using the filter parameter to only return colliders in the main category when you query.

Cached spatial index

Querying is done using a spatial index which is only updated during the physics simulation step of each tick. That means if a query is performed, and then body positions are changed manually, the next query will run on a stale spatial index and so results might not be accurate. You can force the spatial index to be recalculated by calling ResetSpatialQueryIndex.

When a new collider is created, it is automatically added to the spatial index, so you do not need to call ResetSpatialQueryIndex after creating a new collider.

tip

Try to avoid calling ResetSpatialQueryIndex where possible as it is an expensive operation! Consider waiting until the next tick to perform your query when the physics simulation will automatically update the spatial index for you.

Contact graph

The QueryContacts, QueryAnyContact and CountContacts funtions query the contact graph, which is a special data structure that tracks which colliders are currently in contact with each other. This is only updated during the physics simulation step of each tick, and it cannot be updated manually like the spatial index can. ResetSpatialQueryIndex will not affect the contact graph.