Imagine you've written an amazing game with eight different type of sprite, and
suddenly realise you'd like your sprites to have the notion of
visibility / invisibility.
It would be a royal pain in the neck to go through all your coding, making a bunch of new visibility variables and weaving them into your existing work. We can just make the minimal change and all our sprites automatically get it.
We add a property called visible to the object definition:
function MySprite (img_url) {
this.x = 0;
this.y = 0;
this.visible = true;
this.velocity_x = 0;
this.velocity_y = 0;
this.MyImg = new Image();
this.MyImg.src = img_url ;
}
And in the Do_Frame_Things method, we only do the drawImage() if the variable is true.
MySprite.prototype.Do_Frame_Things = function() {
if (this.visible) ctx.drawImage(this.MyImg, this.x, this.y); // draw the thing, but only if it's visible
this.x = this.x + this.velocity_x;
this.y = this.y + this.velocity_y; // move the thing
}
Finally, we enhance ImagesTouching so that if either one of the sprites is not visible, then they cannot be touching.
function ImagesTouching(thing1, thing2) {
//
// This function detects whether two MySprites are touching - very useful function
//
if (!thing1.visible || !thing2.visible) return false;
if (thing1.x >= thing2.x + thing2.MyImg.width || thing1.x + thing1.MyImg.width <= thing2.x) return false;
if (thing1.y >= thing2.y + thing2.MyImg.height || thing1.y + thing1.MyImg.height <= thing2.y) return false;
return true;
}