I have a 2d array of vectors of pointers to Entities in a game. The array represents a grid of game world to improve performance when detecting collisions. When an entity moves I check if it moves over to another grid-tile (of course) but this is where everything goes to hell. If I move the object in the array when it changes tile CPU goes to 100% instead of 8% and game physics no longer apply.
This is the update function where it stops working:
for (int i = 0; i < xGridCount; i++)
{
for (int j = 0; j < yGridCount; j++)
{
for (auto it : grid[i][j])
{
it->update();
//update gridpos
if ((int) it->x/gridSize != i || (int) it->y/gridSize != j)
{
grid[it->x/gridSize][it->y/gridSize].emplace_back(std::move(it));
}
}
}
}
Declaration of grid array:
std::array<std::array<std::vector<std::shared_ptr<Entity>>, yGridCount>, xGridCount> grid;
The "update gridpos" is where it collapses. If I comment it out everything works as it should.
I have, of course, figured what I could do to fix it and I've thought of using the array only in the collision detection. But the thing about that would be that I would have to keep 2 pointers of every object, one for hit detection and one for updating/rendering and that doesn't sound like a good solution.
Why is it so CPU heavy? And how else could I do it?
grid, please show it.