Unity ECS Physics how to use CollisionFilter , RaycastHit [RESLVED]

hi everyone.

  1. is there a way to set a detailed CollisionFilter layers for a RaycastInput ?
    eg : belongsto Projectile , Collides with Players,Environment, Destructables …
                // RayCast Input
                RaycastInput input = new RaycastInput()
                {
                     Start = projectileData.lastFramePosition,
                     End = translation.Value,
                     Filter = CollisionFilter.Default // Standard Filter
                };
  1. how can i get The Collider Layer from a RaycastHit ?
1 Like

What’s stopping you setting the filter layer?

Filter = new CollisionFilter
{
    BelongsTo = 0xffffffff,
    CollidesWith = this.settings.ObserverLayer,
    GroupIndex = 0,
},

You can get the layer of the objects you hit from the Collider

            for (var i = 0; i < hits.Length; i++)
            {
                var body = bodies[hits[i]];
                var filter = body.Collider->Filter

(this requires unsafe context)

1 Like

how can i set muliple layers for the CollidesWith field?
eg i want to specify that my projectile can collide with multiple layers.

where di you find these api ?
the official documentation is outdated.

I don’t really read documentation so I can’t say if it exists there. I just read the source code.

As for your question about layers, CollidesWith is a mask field. 0xffffffff is just the hex code for everything.

If you only want layer 1 or 2 (and not layer 0) for example you could just use

CollidesWith = 1u << 1 | 1u << 2,

It’s very similar to regular LayerMasks

Except it’s a uint

        // Bit shift the index of the layer (8) to get a bit mask
        int layerMask = 1 << 8;

        // This would cast rays only against colliders in layer 8.
        // But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
        layerMask = ~layerMask;
6 Likes

Thanks a lot @tertle !!!

Or just use something like this JacksonDunstan.com | BitArray32 and BitArray64 that makes setting complex masks easy.

I map Unity layers to Unity.Physics layers a lot.

public static CollisionFilter LayerMaskToFilter(LayerMask mask)
        {
            CollisionFilter filter = new CollisionFilter()
            {
                BelongsTo = (uint)mask.value,
                CollidesWith = (uint)mask.value
            };
            return filter;
        }

        public static CollisionFilter LayerToFilter(int layer)
        {
            if (layer == -1)
            {
                return CollisionFilter.Zero;
            }

            BitArray32 mask = new BitArray32();
            mask[layer] = true;

            CollisionFilter filter = new CollisionFilter()
            {
                BelongsTo = mask.Bits,
                CollidesWith = mask.Bits
            };
            return filter;
        }
11 Likes

thank you!
it’s easy of use ^^