Reputation: 865
I am developing an endless runner game, in which the obstacles are created continuously and then moved to the left - so, each obstacle gets invisible for the player in a second or so, but it is not any specific number as the game speed is increasing.
Is there a way to delete each obstacle, for example, three seconds after it's creation, to save some memory/speed the game up a little?
I am using a global definition of an array where the obstacles are stored:
var obstacles = []
Then I create an obstacle:
function display(obstacle) {
obstacle.draw()
// the ".draw" function contains a simple "ctx.drawImage"
}
function display_loader(){
for(i in obstacles){
display(obstacles[i])
}
}
After that, I move the obstacle and check it's position for collisions with a similar functions.
Could you give me a hint, how I could keep the array to contain 3-5 items at max?
Also, would it make some effect of the game speed (considering it is meant to be used on mobile platform), or is it totally unnecessary? Is it perfectly enough to empty the array after starting the game over? (In one game cycle maximum of ~100 items are created). And if so, how exactly should I empty this array? Is obstacles = []
enough?
Upvotes: 1
Views: 165
Reputation: 19782
If you have a fixed maximum number of obstacles on-scren at a time, you could use an array as a circular buffer. Allocate a fixed-size array, and maintain a variable that tells you which index the array "starts" at, and one to tell you how many entries are active.
This may give you additional benefits in that you might be able to re-use the obstacle objects instead of allocating and freeing new ones, which reduces the amount of garbage collection overhead.
Upvotes: 0
Reputation: 4173
You can replace array with queue, and keep shifting it each time you add new element, this way size will be constant (code sample taken from here):
var queue = [];
queue.push(2); // queue is now [2]
queue.push(5); // queue is now [2, 5]
var i = queue.shift(); // queue is now [5]
If fixed-size queue is not enough - do you track when objects become invisible? Is there some coordinate associated with each object? You can rely on this information when do queue shifting, and do shift only when item becomes invisible (but this works only if items are added in same order they disappear).
Upvotes: 1