【发布时间】:2014-08-22 00:01:18
【问题描述】:
希望你一切都好。
我目前正在开发一款游戏,主要用于学习目的,但遇到了一点小问题。我有一个为敌人运行的刻度函数,它控制它的运动并检测它是否与舞台边缘相互作用。如果它到达舞台的边缘,则角度会改变并朝另一个方向移动。一旦发生这种情况,“bounceRate”就会减少,并且一旦bounceRate 达到 0,它就会消失并失去生命。
但是,一旦第一个敌人被移除,生命就会开始不断减少,而不仅仅是一次。一旦敌人的bounceRate 达到0,我已经设法“暂停”了敌人的滴答功能,但是一旦第一个孩子被移除,第二个孩子就不会出现在舞台上。
这里是有问题的代码:
全局刻度函数
function tick(event) {
stage.update(event);
for (enemy in enemyCamp) {
var e = enemyCamp[enemy];
e.tick(event);
}
}
敌人的标记功能
enemy.tick = function(event) {
if (!this.paused) {
this.x += this.vX;
this.y += this.vY;
if (this.bounceRate <= 0) {
if (this.x > canvasWidth || this.x < 0 || this.y > canvasHeight || this.y < 0) {
var bounced = false;
if(!bounced) {
bounced = true;
this.paused = true;
this.bouncedEnemy();
}
}
} else {
if (this.x > canvasWidth + 20) {
this.angle = 180 - randomIntFromInterval(-90, 90);
this.updateEnemy();
}
if (this.x < 20) {
this.angle = 180 - randomIntFromInterval(90, 270);
this.updateEnemy();
}
if (this.y > canvasHeight + 20) {
this.angle = 360 - Math.floor(Math.random() * 180);
this.updateEnemy();
}
if (this.y < 20) {
this.angle = 360 - randomIntFromInterval(180, 360);
this.updateEnemy();
}
}
}
stage.update(event);
}
到达舞台边缘时更新敌人
enemy.updateEnemy = function() {
this.bounceRate--;
this.direction = this.angle * Math.PI / 180;
this.rotation = this.angle;
this.vX = Math.cos(this.direction) * this.speed;
this.vY = Math.sin(this.direction) * this.speed;
}
当敌人“反弹”时
enemy.bouncedEnemy = function() {
lives--;
this.active = false;
displayLives.text = "Lives " + Number(lives).toString();
var displayedEnemys = enemyCamp.getNumChildren();
enemyPen.removeChild(this);
if ((displayedEnemys < level) || (displayedEnemys <= 0)) {
spawnEnemy();
}
stage.update();
}
生成敌人
function spawnEnemy() {
if (level > 1) {
var w = 0;
for (w;w<level;w++) {
spawnRate++;
enemyCamp[spawnRate] = new Enemy();
enemyPen.addChild(enemyCamp[spawnRate]); //Enemy pen is a container
}
} else {
spawnRate++;
enemyCamp[spawnRate] = new Enemy();
enemyPen.addChild(enemyCamp[spawnRate]);
}
stage.update();
}
目前tick函数运行一次,一旦孩子从舞台上移除就停止运行。创建敌人后调用this.paused = false;。有没有办法只为孩子暂停勾选功能,然后在将新孩子添加到舞台后重新开始?这就是我现在的感觉,但我可能是错的。
任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
你没有显示代码,你会在哪里处理具有负反弹率的敌人,这对你的错误来说似乎很重要。
-
感谢您的回复。关于敌人的处置,我所拥有的只是 bouncedEnemy 函数中的这行代码:
enemyCamp.removeChild(this);这是enemyCamp 和enemyPen 的两个变量enemyPen = new createjs.Container();和enemyCamp = [];我刚刚注意到我上面的代码有错误,我现在已经调整了。在bouncedEnemy 函数中它实际上设置为enemyPen.removeChild(this) -
你不是从enemyCamp中移除敌人,而是从enemyPen中移除。但无论如何,分享你的 codePen 怎么样?
-
我会尽快为您设置一个 codePen 的东西。
标签: javascript html5-canvas easeljs