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

ECS + Jobs. How to: "each entity interacts with all other entities"

Discussion in 'Entity Component System' started by Zolden, Mar 7, 2020.

  1. Zolden

    Zolden

    Joined:
    May 9, 2014
    Posts:
    141
    I would like to figure the best or at least some way to do this particular thing with ECS + Jobs. There's a big array of interacting particles. Each particle should check each other particle of the array, measure distance and exchange forces.

    So, a job that is being run for a particular particle, should also have a way to access all other particles. How to do this?

    Right now I derive my job from IJobForEach<>, which gives access to one instance of the component. I guess, there's more appropriate kind of IJob... interface, that would allow to access not only current component, but all others as well. Any tips?
     
  2. SamOld

    SamOld

    Joined:
    Aug 17, 2018
    Posts:
    333
    If you just want to be able to read from other entities,
    ComponentDataFromEntity<T>
    is probably what you're looking for.

    You could get all of the particles by simply iterating over them twice. The first time builds up a list, the second time does the updating using that list of other particles. There may be an API that gives you that list from a query without having to build it yourself, but I don't know it.

    With a many to many interaction like this and assuming you have a large number of particles, you may find that the best performance comes from an algorithmic change. You probably only need to precisely compute forces for other particles within a fairly small radius. You should be able to get this down from O(n^2) O(n log n). First iterate over all particles and write them into some form of accelerated spacial lookup structure, then iterate over the particle entities again and get their forces by doing a lookup in that structure. N body simulation is a good keyword if you want to look into these algorithmic optimisations.
     
  3. TheGabelle

    TheGabelle

    Joined:
    Aug 23, 2013
    Posts:
    242
    SamOld likes this.