我真的很难想出一个标题,但基本上我正在使用html5画布上的游戏,并且在与ai对战时有一个名为player的子类aiPlayer。更新玩家的代码如下:
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更新功能进行更新。我已经打印出每个实体的构造函数,并且有一个Player和一个aiPlayer。但是,当打印出他们正在调用的方法时,他们都调用了Player更新。有谁知道为什么会这样做? 此外,如果有帮助,aiPlayer更新如下:
aiPlayer.prototype.update = function() {
if((this.game.timer.gameTime % this.moveTime) > (this.moveTime * 0.9)) {
this.chooseMove();
}
Player.prototype.update.call(this);
};
ai构造函数看起来像:
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";
}
答案 0 :(得分: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
已注册为其构造函数< / p>
此外,.update
的{{1}}是从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
)