Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Question Finding colliders inside another collider without mesh triangles intersecting.

Discussion in 'Physics for ECS' started by Dan-Foster, Jan 18, 2023.

  1. Dan-Foster


    Aug 7, 2019
    Hi there,

    I'm trying to check to see if one mesh collider contains other colliders of a certain type (ie the player is inside a room).

    If I do a PhysicsWorld.CastCollider( ColliderAspect ) with a distance of 0, then it will only report true if the player is intersecting with a triangle of the mesh used in the PhysicsShape.

    After writing the code and seeing this effect happen I do understand that the physics system is sweeping the triangles of the mesh and reporting any intersections, but it's not my desired behaviour.

    What I want is to be able to treat the PhysicsShape as a solid object and know if the player is intersecting it. In this case the player can be sat completely inside this volume, but because they're not touching the sides they aren't detected.

    I have some example code below that's side stepping the issue by doing an AABB check then sweeping the collider up then down by the AABB height. But it seems like it's the long way round.

    Also you'll note from the code that the code doesn't yet handle actually counting the number of players inside the volume which will add to the code complexity for my solution as it's going to have to return the NativeList<ColliderCastHit> results of both CastCollider calls.

    Is there an easier way to do this?

    Code (CSharp):
    1.     [BurstCompile]
    2.     [WithAll( typeof( RiftCollider ) )]
    3.     private unsafe partial struct RiftVolumeTriggerJob : IJobEntity
    4.     {
    5.         [ReadOnly]
    6.         public PhysicsWorld physicsWorld;
    8.         public NativeArray<int> playersInside;
    10.         [BurstCompile]
    11.         public unsafe void Execute( in ColliderAspect collider )
    12.         {
    13.             NativeList<int> hits = new NativeList<int>( Allocator.Temp );
    14.             var aabb = collider.CalculateAabb();
    16.             bool aabbCheck = physicsWorld.OverlapAabb( new OverlapAabbInput
    17.             {
    18.                 Aabb = aabb,
    19.                 Filter = collider.GetCollisionFilter()
    20.             }, ref hits );
    22.             if( aabbCheck
    23.                 && physicsWorld.CastCollider( in collider, math.up(), aabb.Extents.y )
    24.                 && physicsWorld.CastCollider( in collider, math.down(), aabb.Extents.y ) )
    25.             {
    26.                 playersInside[0] += 1;
    27.             }
    28.         }
    29.     }
    mcroswell likes this.