Overview
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.
Example
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);
};
};
Js Fiddle
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!