Mugen87 / yuka

JavaScript library for developing Game AI.
https://mugen87.github.io/yuka/
MIT License
1.1k stars 90 forks source link

Efficient way to find an intersection #42

Closed YuryKonvpalto closed 3 years ago

YuryKonvpalto commented 3 years ago

Hi guys,

what would be a most efficient way to find an intersection between given entities? Say, we have static entities and a vehicle. Naive approach would be to iterate all entities each worldstep and compare their boundig spheres with a BS of vehicle. But if we have 100 entities it would have an impact on game perfomance. Is there any variant in Yuka that makes intersection's search more efficient? I guess may be a Cell division (cell-space partitioning) has smthg to do with it, but not sure...

Mugen87 commented 3 years ago

I guess may be a Cell division (cell-space partitioning) has smthg to do with it, but not sure...

Yes, the class CellSpacePartitioning (which is nothing else than a simple spatial index) is the right choice for this use case.

The idea is to divide up the 3D space into cells. You can then determine the so called neighborhood of a game entity. The neighborhood represents a collection of other game entities which are close enough for a potential collision.

BTW: You don't have to compute the neighborhood by yourself. You can set GameEntity.updateNeighborhood to true so the EntityManager automatically computes the neighborhood based on GameEntity.neighborhoodRadius. You can then access the neighbors by accessing the read-only array property GameEntity.neighbors.

To speed up this process, assign an instance of CellSpacePartitioning to EntityManager.spatialIndex. Watch out to make the spatial index large enough so it encloses your game environment. The ideal cell size depends on your use case. You can visualize the spatial index for debugging purpose like in this example.

YuryKonvpalto commented 3 years ago

Thanks a lot for a tip with neighbours! And will dig deep into proposed example (studied it before, but overlooked it uses a CSP).