Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question CollisionEvent firing when objects are not colliding

Discussion in 'Physics for ECS' started by slushieboy99, Sep 8, 2023.

  1. slushieboy99

    slushieboy99

    Joined:
    Aug 29, 2014
    Posts:
    86
    Hi all,
    I have a job which uses CollisionEvent to run when a collision happens, however this job is running many times per frame when no collisions should be happening. I'm testing this by instantiating a few thousand entities with the following Physics Shape:

    upload_2023-9-8_15-20-21.png

    As seen above, I've tested this with 'Collides With' set to none and it's still causing the job to fire per entity. When I disable this physics shape component the job does not fire at all. Could someone explain to me why this is happening and if there's a better way to handle collision triggers?

    Below is my job code if it helps:
    Code (CSharp):
    1. public struct UpdateGroundedTagJob : ICollisionEventsJob {
    2.     public ComponentDataFromEntity<TerrainTag> terrainTags;
    3.     public ComponentDataFromEntity<MovableComponent> movableComponents;
    4.     public ComponentDataFromEntity<GroundedTag> groundedTags;
    5.     public EntityCommandBuffer ECB;
    6.  
    7.     public void Execute(CollisionEvent collisionEvent) {
    8.         var entityA = collisionEvent.EntityA;
    9.         var entityB = collisionEvent.EntityB;
    10.  
    11.         var isBodyAGrounded = groundedTags.HasComponent(entityA);
    12.         var isBodyBGrounded = groundedTags.HasComponent(entityB);
    13.  
    14.         var isBodyATerrain = terrainTags.HasComponent(entityA);
    15.         var isBodyBTerrain = terrainTags.HasComponent(entityB);
    16.  
    17.         if (isBodyATerrain && isBodyBTerrain) {
    18.             return;
    19.         }
    20.  
    21.         var isBodyAMovable = movableComponents.HasComponent(entityA);
    22.         var isBodyBMovable = movableComponents.HasComponent(entityB);
    23.  
    24.         if ((isBodyATerrain && !isBodyBMovable) || (isBodyBTerrain && !isBodyAMovable)) {
    25.             return;
    26.         }
    27.  
    28.         var selectedUnit = isBodyATerrain ? entityB : entityA;
    29.         MovableComponent movableComponent = movableComponents[selectedUnit];
    30.         movableComponent.framesSinceGrounded = 0;
    31.         movableComponents[selectedUnit] = movableComponent;
    32.  
    33.         if (isBodyAGrounded || isBodyBGrounded) {
    34.             return;
    35.         }
    36.  
    37.         ECB.AddComponent<GroundedThisFrameTag>(selectedUnit);
    38.         ECB.AddComponent<GroundedTag>(selectedUnit);
    39.     }
    40. }
     
  2. slushieboy99

    slushieboy99

    Joined:
    Aug 29, 2014
    Posts:
    86