Search Unity

Resolved How to change the CollisionFilter at Runtime

Discussion in 'Physics for ECS' started by KANIYO, Jun 4, 2023.

  1. KANIYO

    KANIYO

    Joined:
    Nov 12, 2020
    Posts:
    28
    I want my character to collide with A when he is in the air but not when he is on the ground.
    So I have looked for a way to change the CollisionFilter during the runtime but could not find it.

    How do I change the CollisionFilter at runtime?
     
  2. KANIYO

    KANIYO

    Joined:
    Nov 12, 2020
    Posts:
    28
    I was able to solve this problem with the help of this post.
    https://forum.unity.com/threads/collisionfilter-authoring.1437421/


    using Unity.Physics;
    using Unity.Physics.Systems;
    using Unity.Physics.Extensions;


    BlobAssetReference<Collider> ColliderBlobReference = physicsCollider.ValueRO.Value.Value.Clone();
    CollisionFilter oldFilter = physicsCollider.ValueRO.Value.Value.GetCollisionFilter();
    PhysicsCollider newCollider;

    ColliderBlobReference.Value.SetCollisionFilter(new CollisionFilter
    {
    BelongsTo = 0b_0000_0000_0000_0000_0000_0000_0000_0000,
    CollidesWith = 0b_0000_0000_0000_0000_0000_0000_0000_0000,
    GroupIndex = oldFilter.GroupIndex,
    });
    newCollider = ColliderBlobReference.AsComponent();
    ECB.SetComponent(sortKey, entity, newCollider);



    It seems costly to copy the PhysicsCollider, which is a BlobAsset, apply a new CollisionFilter and SetComponent again, but I think I will go with this.



    Note that I first tried to turn the Collider on and off by preparing two children and applying a different CollisionFilter to each, and setting the CollisionWorldIndex to a value not used (such as 10) depending on the situation, but this failed.

    Thank you very much.
     
    Last edited: Jun 6, 2023
    kro11 likes this.
  3. zb737472783

    zb737472783

    Joined:
    Nov 8, 2018
    Posts:
    19
    It worked!
     
    KANIYO likes this.