Suppose my base class is the following:
function Tile(obj) {
//defaults (alot of variables here like colors and opacity)
}
Tile.prototype.Draw = function () {
ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," + this.Opacity + ")";
ctx.fillRect(this.X, this.Y, this.Width, this.Height);
};
my class that inherits from the Tile class
Apple.prototype = new Tile();
Apple.prototype.constructor = Apple;
function Apple(obj) {
Tile.apply(this, arguments);
}
So what I would like to do with my apple objects is have its opacity fluctuate between 0 and 1 so that it constantly fades in and out but I would like this to happen independently of the ‘game loop’. (So that the fading animation is smooth regardless of the game speed)
function StartGameLoop() {
console.log("*** Starting Game ***");
gameLoop = setInterval(Game, gameSpeed);
}
function Game() {
if (!IS_GAME_ON) { // Did the game end?
EndGame();
} else if (!PAUSE) { // Is the game not paused?
console.log("Tick");
Logic(); // do any math
}
}
I can’t wrap my head around how to do this but I had an idea of putting a setInterval in the Apple constructor that calls the draw function over and over again but I can’t get it to work. Like this:
Apple.prototype = new Tile();
Apple.prototype.constructor = Apple;
function Apple(obj) {
var AnimationDirection;
var animate = setInterval(this.Draw, 50);
Tile.apply(this, arguments);
}
Apple.prototype.Draw = function () {
ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," + this.Opacity + ")";
ctx.fillRect(this.X, this.Y, this.Width, this.Height);
if (this.Opacity <= 0) {
this.AnimationDirection = 0.1;
}
else if (this.Opacity >= 1) {
this.AnimationDirection = -0.1;
}
this.Opacity += this.AnimationDirection;
};
It works as you’d expect when the first Apple.Draw() is called but the calls from the setInterval are not working properly. Any ideas?
(PS: Also the two ctx lines in the Draw function are repeated in both the Tile and the Apple classes, is there any way I can kick it to the Tile parent for the filling instead of having the code duplication?)
I believe the cause is that when the
Draw()function fires as part of thesetIntervalcall,thisisn’t what you think it is.Instead, use a variable inside your constructor to store the value of
thiswhen it refers to the Apple object created, and use an anonymous function forsetInterval()to be able to refer to that new variable and call theDraw()function correctly on it, e.g. something like:Since you are now calling the
Draw()method on anAppleobject (rather than the global window),thiswill correctly refer to that object.