这可能是一个冗长的帖子。我必须在飞行中学习JS,并且可能会犯很简单的错误。
我用JS / html编写游戏,并使用EasyStar为某些实体添加一些寻路行为。我使用继承将下面Walker4
中概述的行为提供给多个实体,例如底部的实例:
function Walker4(game, img, Ai, lX, lY) {
this.easyStar = Ai;
this.dX = 0;
this.dY = -1;
this.animation = [];
this.animation["NE"] = null;
this.animation["NW"] = null;
this.animation["SE"] = null;
this.animation["SW"] = null;
this.currAnimation = null;
this.facing = "";
this.img = img;
this.isWalking = false;
this.isFindingPath = false;
this.destX = null;
this.destY = null;
this.path = [];
this.next = null;
this.loadCount = 0;
Entity.call(this, game, lX, lY);
}
Walker4.prototype = new Entity();
Walker4.prototype.constructor = Walker4;
Walker4.prototype.update = function () {
if (this.isFindingPath) return;
if (this.isWalking) this.walkPath();
if (this.destX != null && this.destY != null) {
this.isFindingPath = true;
that = this;
easyStar.findPath(this.x, this.y, this.destX, this.destY, function (path) {
if (path === null) {
console.log("No path :(");
} else {
console.log("Path! The first Point is " + path[0].x + " " + path[0].y);
that.path = path;
that.next = that.path.shift();
that.isWalking = true;
}
});
this.destX = null;
this.destY = null;
this.isFindingPath = false;
easyStar.calculate();
}
Entity.prototype.update.call(this);
}
Walker4.prototype.walkPath = function () {
if (this.path.length == 0) {
if (Math.floor(this.x) == this.next.x && Math.floor(this.y) == this.next.y) {
this.dX = 0;
this.dY = 0;
}
isWalking = false;
return;
}
if (Math.floor(this.x) == this.next.x && Math.floor(this.y) == this.next.y) {
this.next = this.path.shift();
this.dX = setDirection(Math.floor(this.x), this.next.x);
this.dY = setDirection(Math.floor(this.y), this.next.y);
this.currAnimation = this.animation[setFace(this.dX, this.dY)];
}
this.x += this.dX * this.game.clockTick * speed;
this.y += this.dY * this.game.clockTick * speed;
}
Walker4.prototype.draw = function (ctx) {
pt1 = twodtoisoX(this.x, this.y) + 27 - this.currAnimation.frameWidth / 2;
pt2 = twodtoisoY(this.x, this.y) + 10 - this.currAnimation.frameHeight / 2;
ctx.fillRect(pt1, pt2, 5, 5);
//console.log(pt1, pt2);
this.currAnimation.drawFrame(this.game.clockTick, ctx, pt1, pt2);
Entity.prototype.draw.call(this);
}
//Cart Walkers
function eCartMan(game, img, Ai, lX, lY) {
Walker4.call(this, game, img, Ai, lX, lY);
this.animation["NE"] = new Animation(img, 0, 0, 60, 48, 12, aSpeed, 12, true);
this.animation["NW"] = new Animation(img, 0, 1, 60, 48, 12, aSpeed, 12, true);
this.animation["SE"] = new Animation(img, 0, 2, 60, 48, 12, aSpeed, 12, true);
this.animation["SW"] = new Animation(img, 0, 3, 60, 48, 12, aSpeed, 12, true);
this.currAnimation = this.animation["NE"];
}
eCartMan.prototype = new Walker4();
eCartMan.prototype.constructor = eCartMan;
所有这些实体都被添加到每个游戏标记中循环更新的实体列表中,每个实体分别调用update
和draw
。 Easy Star似乎为每个实体提供了一条路径,但只有最近添加的实体才会实际遵循其给定的路径。我错过了什么?
任何帮助表示赞赏。
答案 0 :(得分:1)
好吧,确定问题的范围。感谢@HMR的帮助。
在that = this;
上结束了范围问题,并且每个步行者都需要自己版本的EasyStar探路者。 that
变得全球化,并且打开了步行者的所有实例以相互修改。