tl;dr collision filter does not seem to take effect.
I’ve setup a minimal Unity project with just 1 cube and 1 script:
- Cube is in layer 8. (Fig 1)
- 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();
}
}
- I’ve looked through the Github examples https://github.com/Unity-Technologies/EntityComponentSystemSamples/search?utf8=✓&q=CollisionFilter&type= but most cases involve setting up a collider for an entity, instead of running a collision query.
- The demos in the Getting Started https://docs.unity3d.com/Packages/com.unity.physics@0.2/manual/collision_queries.html are more similar, so I tried to pattern match.
- The above code is based off of Best way to find Closest Target Entity? .
- Admittedly, I didn’t fully understand what a group index is; which value “in both objects” are the docs referring to?