Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Hybrid ECS collision tracking

Discussion in 'Entity Component System' started by Orimay, May 1, 2018.

  1. Orimay

    Orimay

    Joined:
    Nov 16, 2012
    Posts:
    304
    Is there a best practice for the ECS collision tracking? We don't have events and we may have multiple collisions/trigger interactions during the frame. Did anyone come up with a nice solution for 3D yet?
     
  2. Spy-Shifty

    Spy-Shifty

    Joined:
    May 5, 2011
    Posts:
    546
    Create entites with a CollisionComponent attached to it.

    Code (CSharp):
    1.  
    2. struct CollisionComponent : IComponentData {
    3.       public Entity source;
    4.       public Entity other;
    5. }
    6.  
    7.  
    8. public CollisionEmitter : Monobehaviour {
    9.  
    10.     public void OnCollisionEnter(Collider other) {
    11.          GameObjectEntity otherGameObjectEntity = other.GetComponent<GameObjectEntity>();
    12.          if(!otherGameObjectEntity) {
    13.                return;
    14.          }
    15.      
    16.          Entity sourceEntity = GetComponent<GameObjectEntity>().Entity;
    17.          var entityManager = World.Active.GetExistingManager<EntityManager>();
    18.          Entity collisionEventEntity = entityManager.CreateEntity(typeof(CollisionComponent));
    19.          entityManager.SetComponentData(collisionEventEntity, new CollisionComponent {
    20.                source = sourceEntity,
    21.                other = otherGameObjectEntity.Entity,
    22.          });
    23.      }
    A system should handle it and destroy the created entities after handling.
    This way you can build events in ECS
     
    Mrb83, Singtaa, Orimay and 2 others like this.
  3. Orimay

    Orimay

    Joined:
    Nov 16, 2012
    Posts:
    304
    Thank you!
     
  4. Orimay

    Orimay

    Joined:
    Nov 16, 2012
    Posts:
    304
    Though I think NativeMultiHashMap should be used here. Otherwise it will take a loop over all the collision entities once we need a collision for any specific entity
     
  5. Orimay

    Orimay

    Joined:
    Nov 16, 2012
    Posts:
    304
    Or there would be a Collision component with NativeList of Collision components, that contain Entity, hit point, hit normal etc. We could reset such list in a system, that refills it by CmdCollision, prodused by a MonoBehaviour as in Spy-Shifty's sample