2015-03-15 2 views
1

Я действительно боролся с заголовком, но в основном я работаю над игрой в холсте html5 и имею класс под названием player с подклассом aiPlayer, когда вы играете против ai. Код для обновления игроков выглядит следующим образом:функция суперкласса вызывается при вызове функции подкласса

var entitiesCount = this.entities.length; 
    for (var i = 0; i < entitiesCount; i++) { 
     var entity = this.entities[i]; 
     entity.update(); 
     if (entity instanceof special && entity.x > WIDTH || entity.x + 200 < 0) { 
      this.entities.splice(i, 1); 
      entitiesCount--; 
     } 
    } 

Однако aiPlayer никогда не обновляется с помощью функции обновления aiPlayer. Я распечатал конструктор каждого объекта, и есть один игрок и один aiPlayer. Однако при печати метода, который они вызывают, оба они вызывают обновление плеера. Кто-нибудь знает, почему он это сделает? Кроме того, если это поможет, то обновление aiPlayer выглядит следующим образом:

aiPlayer.prototype.update = function() { 
    if((this.game.timer.gameTime % this.moveTime) > (this.moveTime * 0.9)) {   
     this.chooseMove(); 
    } 
    Player.prototype.update.call(this); 
}; 

И аи конструктор выглядит следующим образом:

function aiPlayer (game, character, x, y, health) { 
    Player.call(this, game, character, x, y, health, PLAYER2_CONTROLS, "left"); 
    aiPlayer.prototype = new Player(this.game, this.character, this.x, this.y, 
           this.health, this.control, this.facing); 
    aiPlayer.prototype.constructor = aiPlayer; 
    this.controls = PLAYER2_CONTROLS; 
    this.attackLength = 50; 
    this.fleeLength = 70; 
    this.moveTime = 1; 
    this.prevControl = "idle"; 
} 

ответ

1
function aiPlayer (game, character, x, y, health) { 
    Player.call(this, game, character, x, y, health, PLAYER2_CONTROLS, "left"); 
    aiPlayer.prototype = new Player(this.game, this.character, this.x, this.y,this.health, this.control, this.facing); 
    aiPlayer.prototype.constructor = aiPlayer; 
    this.controls = PLAYER2_CONTROLS; 
    this.attackLength = 50; 
    this.fleeLength = 70; 
    this.moveTime = 1; 
    this.prevControl = "idle"; 
} 

Эти линии здесь

aiPlayer.prototype = new Player(this.game, this.character, 
           this.x, this.y,this.health, 
           this.control, this.facing); 
aiPlayer.prototype.constructor = aiPlayer; 

неверны. Они не правы, потому что

  • вы устанавливаете прототип к экземпляру Player
  • вы перезагружаете прототип и конструктор прототипа aiPlayer каждый раз, когда вы создаете новый экземпляр aiPlayer. Вы должны переместить все изменения в прототипе за пределами функции конструктора, например:

-

function aiPlayer (game, character, x, y, health) { 
    Player.call(this, game, character, x, y, health, PLAYER2_CONTROLS, "left"); 
    this.controls = PLAYER2_CONTROLS; 
    this.attackLength = 50; 
    this.fleeLength = 70; 
    this.moveTime = 1; 
    this.prevControl = "idle"; 
} 

aiPlayer.prototype.someMethod = function someMethod() { 
    .... 
} 

Правильный способ установить прототип подкласса, как это

aiPlayer.prototype = Object.create(Player.prototype, { 
    constructor : { 
     value : aiPlayer 
    } 
}; 

В качестве прототипа aiPlayer будет установлен новый объект, который наследует от Player.prototype (т.е. имеет Player.prototype в качестве прототипа) и имеет aiPlayer reg istered в качестве конструктора функции

Кроме того, .update из Player вызывается из aiPlayer, потому что вы явно вызывая его здесь

aiPlayer.prototype.update = function() { 
    if((this.game.timer.gameTime % this.moveTime) > (this.moveTime * 0.9)) {   
     this.chooseMove(); 
    } 
    Player.prototype.update.call(this); //you call the Player.update() 
}; 

Учитывая вышесказанное, это то, как вы должны зарегистрировать aiPlayer.update

aiPlayer.prototype = Object.create(Player.prototype, { 
    constructor : { 
     value : aiPlayer 
    } 
}; 

aiPlayer.prototype.update = function update() { 
//your code here 
} 

Теперь, когда вы создаете новый экземпляр объекта aiPlayer, цепочка наследования будет выглядеть следующим образом:

aiPlayerInstance --> aiPlayer.prototype --> Player.prototype 

и при вызове aiPlayerInstance.update() будет первым смотреть aiPlayer.prototype и так aiPlayer.prototype имеет метод, называемый update он будет выполнять его, и он не будет смотреть дальше вниз по цепочке наследования (т.е. в Player.prototype)

Смежные вопросы