CollisionFilter not taking effect for CollisionWorld.CalculateDistance

tl;dr collision filter does not seem to take effect.

I’ve setup a minimal Unity project with just 1 cube and 1 script:

  1. Cube is in layer 8. (Fig 1)
  2. I have one TestComponentSystem.cs that calculates distance to the entity closest to the cube. Despite a CollisionFilter that says to ignore the cube’s layer 8, the closest hit is always the cube itself. I’d expect the calculate distance function to return no entities. (full file source in Fig 2)

Question: Am I misusing the CollisionFilter? Is my group index set incorrectly?

Fig 1: Cube has standard cube GO components + physics body, physics shape, convert to entity.

image

Fig 2: source code for TestComponentSystem.

TestComponentSystem.cs

using Unity.Entities;
using Unity.NetCode;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Transforms;
using Unity.Collections;
using Unity.Physics.Systems;
using Unity.Physics.Extensions;

public class TestComponentSystem : ComponentSystem
{
    BuildPhysicsWorld physicsWorldSystem;

    protected override void OnCreate()
    {
        physicsWorldSystem = World.GetOrCreateSystem<BuildPhysicsWorld>();
        base.OnCreate();
    }

    protected void FindClosestTarget()
    {
        Entities.ForEach((Entity entity, ref Translation trans, ref PhysicsCollider col) =>
        {
            CollisionWorld collisionWorld = physicsWorldSystem.PhysicsWorld.CollisionWorld;

            DistanceHit closestHit;


            CollisionFilter filter = new CollisionFilter
            {
                BelongsTo = ~(1u << 8),
                CollidesWith = ~(1u << 8),
                GroupIndex = 0
            };

            PointDistanceInput input = new PointDistanceInput
            {
                Position = trans.Value,
                MaxDistance = 10,
                Filter = filter
            };

            if (collisionWorld.CalculateDistance(input, out closestHit))
            {
                Entity other = collisionWorld.Bodies[closestHit.RigidBodyIndex].Entity;
                UnityEngine.Debug.Log(other);
            }
        });
    }

    protected override void OnUpdate()
    {
        FindClosestTarget();
    }
}

This is resolved now. I got confused by the overloaded “layers” name. The “layers” that the documentation refers to is not the “traditional” Unity layer. In the physics shape component UI, the “Collision Filter” drop down has a BelongsTo field that contains physics-specific layers.

image of collision filter in physics body

As for understanding group index, the code sample in that section explains more concisely: https://docs.unity3d.com/Packages/com.unity.physics@0.2/manual/collision_queries.html#filtering

1 Like