Hi All! - I'm creating a side scroller space shooter (similar to games of old, still learning!) - and I'm wondering how to better manage my objects in order to prevent wasted resources!
So, In my code, I have created an IIFE for the Player and a constructor for projectiles. The player listens for clicks on the game's canvas and when it hears one, it creates a projectile and attaches it to an object within the Player. However, when a projectile reaches the right hand side of the screen, I want it to be destroyed, for it to be removed from the players projectiles object, and for all update and draw functions for the projectile to end. I've so far managed to stop it drawing and updating, but I haven't been able to remove it from the Players projectile object yet. Hopefully the code below will better demonstrate what I'm attempting to do.
var Player = (function () {
var width = 50;
var height = 50;
var x = 0;
var y = 0;
var projectiles = [];
var update = function () {
for (var p = 0; p < projectiles.length; p++) {
if(!projectiles[p].destroyed)projectiles[p].update();
}
};
var draw = function () {
Canvas.context.fillStyle = 'white';
Canvas.context.fillRect(x, y, width, height);
for (var p = 0; p < projectiles.length; p++) {
if(!projectiles[p].destroyed)projectiles[p].draw();
}
};
Canvas.bindEvent('mousemove', function (e) {
//x = e.pageX - Canvas.element.getBoundingClientRect().left;
y = e.pageY - Canvas.element.getBoundingClientRect().top;
});
Canvas.bindEvent('click', function () {
projectiles.push(new Projectile(width, y + (height / 2)));
});
return {
draw: draw,
update: update
}
})();
var Projectile = function (x, y) {
this.w = 10;
this.h = 10;
this.x = x;
this.y = y;
this.speed = 5;
this.destroyed = false;
this.update = function () {
this.x += this.speed;
if(this.x > Canvas.element.width){
this.destroyed = true;
this.x = 0;
console.log('Projectile Destroyed!');
}
};
this.draw = function(){
Canvas.context.fillStyle = 'red';
Canvas.context.fillRect(this.x, this.y, this.w, this.h);
};
};
Here's my current code in a semi-working JS fiddle, so the code above can be viewed in context. If this question isn't clear, please let me know in the comments and I'll do my best to give clarification. Thanks all!
You could remove the destroyed one in the update method, but you 'll need to loop from the end of the array.
var update = function () {
for (var p = projectiles.length - 1; p >= 0; p--) {
if(!projectiles[p].destroyed)projectiles[p].update();
else projectiles.splice(p,1);
}
};
Suppose you have a basic loop from 0 to X. If you remove an element at index 0 the array will shift, that mean the object at index 1 will be at index 0. But the next loop will do i++ then the object that is at index 0 will not be checked.