Issue to solve
I'm currently working on a web game where I want to have many dynamic objects. These need to know when they collide with the environment, as well as when they collide with each other and the player. Here is a quick post about how I solved it.
My solution
I use PixiJS and combined it with SAT.js for collision detection.
- I create a grid for the game world. Each cell in the grid manages lists of the objects in it and triggers the update in the objects each frame.
- Each object begins the game with finding the cell(s) they belong to. On each update they check collision against the rest of the objects in the cell(s) and do not need to worry about the rest of the game world.
- When objects have moved the distance from the cell edge of last check, they re-check what cell(s) they are in. They first check the cell(s) they already know they are in, then if no longer found, check the surrounding cells.
- Cells check if they are visible on the screen. If not, they limit their update rate. Instead of each frame, they switch to one time per second. The cell update rate affects all the objects in it and objects update in larger jumps to compensate.
- Objects can limit their updates, for the whole object or specific type of collision/interaction.
This solution allows for filling (for testing purposes...) the screen with dynamic objects while maintaining the frame rate. In the image there are 4000 dynamic zombies, 400 dynamic survivors, 40 static objects and dynamic player. You see about 2/3 of the world, so most of the objects are visible and fully active. Making the game world larger would in this case only improve performance as more objects would be in cells that updates only 1 time per second.
This is on a laptop with 4th gen i7 and IntelHD 4600 for graphics, by no means a very powerful machine. It can maintain 60 fps up to about 6000 zombies and 1000 survivors. The game is meant to be for both computers and mobile platforms, the final game will only have about 1000 and 100 at a time. On my phone, which I would say is about average or a bit below, it can almost maintain 60 at this level. For my phone I'm aiming for the final game to run at minimum 30. All in all plenty of room to work with to get the rest of the functionality in place!