I have a player sprite that must collide with blocks in the world. However, I don’t want to use a for loop to check every single block in the world every tick, so what can I do? My idea was to get the player’s current position, and only check blocks around the player. Is this a good idea?
That’s basically what I’d do. Get the player’s position, subtract and then do small loops to check the tiles around the player…
for (int searchX = playerX - 1; searchX == playerX + 1; searchX ++)
{
for (int searchY = playerY - 1; searchY == playerY + 1; searchY ++)
{
//check for collision
}
}
This is definitely a good idea if you have many non-colliding objects and have profiled your application and found it to be slow in this area(!).
However for it to work, you must have some kind of data structure that allows efficient lookup of nearby tiles, for example a equality spaced grid.
In my game Hydro Hydra - 2nd Dive I have used such a grid to sacrifice some amount of memory in exchange of performance.
However I don’t think I can stress this enough:
Unless you have no deadlines and do it for the fun of it, avoid premature optimization!
- Scarzzurs