Hybrid ECS collision tracking

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?

Create entites with a CollisionComponent attached to it.

struct CollisionComponent : IComponentData {
      public Entity source;
      public Entity other;
}


public CollisionEmitter : Monobehaviour {

    public void OnCollisionEnter(Collider other) {
         GameObjectEntity otherGameObjectEntity = other.GetComponent<GameObjectEntity>();
         if(!otherGameObjectEntity) {
               return;
         }
      
         Entity sourceEntity = GetComponent<GameObjectEntity>().Entity;
         var entityManager = World.Active.GetExistingManager<EntityManager>();
         Entity collisionEventEntity = entityManager.CreateEntity(typeof(CollisionComponent));
         entityManager.SetComponentData(collisionEventEntity, new CollisionComponent {
               source = sourceEntity,
               other = otherGameObjectEntity.Entity,
         });
     }

A system should handle it and destroy the created entities after handling.
This way you can build events in ECS

5 Likes

Thank you!

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

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