I'm running through a HTML5 game tutorial and came across the function below. Can anyone explain how this function works?
var super_update = self.update;
self.update = function(){
super_update();
self.attackCounter += self.atkSpd;
}
I'm not sure why you would need this type of function, the logic seems confusing.
Why would we need a variable called super_update
?
//------------------------- Full code -------------------//
Player = function(){
var self = Actor('player','myId',50,40,30,5,20,20,'green',10,1);
self.updatePosition = function(){
if(self.pressingRight)
self.x += 10;
if(self.pressingLeft)
self.x -= 10;
if(self.pressingDown)
self.y += 10;
if(self.pressingUp)
self.y -= 10;
var super_update = self.update;
self.update = function(){
super_update();
if(self.hp <= 0){
var timeSurvived = Date.now() - timeWhenGameStarted;
console.log("You lost! You survived for " + timeSurvived + " ms.");
startNewGame();
}
}
self.pressingDown = false;
self.pressingUp = false;
self.pressingLeft = false;
self.pressingRight = false;
return self;
}
Entity = function(type,id,x,y,spdX,spdY,width,height,color){
var self = {
type:type,
id:id,
x:x,
y:y,
spdX:spdX,
spdY:spdY,
width:width,
height:height,
color:color,
};
self.update = function(){
self.updatePosition();
self.draw();
}
self.draw = function(){
ctx.save();
ctx.fillStyle = self.color;
ctx.fillRect(self.x-self.width/2,self.y-self.height/2,self.width,self.height);
ctx.restore();
}
self.getDistance = function(entity2){ //return distance (number)
var vx = self.x - entity2.x;
var vy = self.y - entity2.y;
return Math.sqrt(vx*vx+vy*vy);
}
self.updatePosition = function(){
self.x += self.spdX;
self.y += self.spdY;
if(self.x < 0 || self.x > WIDTH){
self.spdX = -self.spdX;
}
if(self.y < 0 || self.y > HEIGHT){
self.spdY = -self.spdY;
}
}
return self;
}
Actor = function(type,id,x,y,spdX,spdY,width,height,color,hp,atkSpd){
var self = Entity(type,id,x,y,spdX,spdY,width,height,color);
self.hp = hp;
self.atkSpd = atkSpd;
self.attackCounter = 0;
self.aimAngle = 0;
var super_update = self.update; // WHAT IS THIS FOR?
self.update = function(){
super_update();
self.attackCounter += self.atkSpd;
}
self.performAttack = function(){
if(self.attackCounter > 25){ //every 1 sec
self.attackCounter = 0;
generateBullet(self);
}
}
return self;
}