JavaScript游戏;阵中的子弹;当我开枪时,阵列中的所有子弹都会从玩家的任何地方重新开始

时间:2013-05-17 20:39:12

标签: javascript

这里有一个小提琴 - http://jsfiddle.net/Ey2eK/1/

但我认为问题部分是这些功能。这个在我的主游戏循环结束时加载:

 playerBullets.forEach(function() {
            if (this.x > WIDTH || this.x < 0 || this.y > HEIGHT || this.y < 0) { this.active = false;}
            playerBullets = playerBullets.filter(function(bullet) {
            return this.active;});

            bulletUpdate(this);
            bulletDraw(this);
          }); 

好的,所以我在这里尝试循环播放playerBullets数组,对于每个子弹,首先我检查它是否超出界限并删除子弹,如果是,然后我加载bulletUpdate来更新子弹位置,这是这个公式:

bulletUpdate = function() {
    this.x += this.xVelocity;
    this.y += this.yVelocity;
  }; 

我在这里的意思是,对于阵列中的每个子弹,它的x和y位置都会因速度变量而增加。

然后在我计算出子弹的新位置后,我用bulletDraw绘制它:

bulletDraw = function() {
    c.beginPath();
    c.save();
    c.translate(this.x,this.y);
    if (deltaX < 0) {
    c.rotate(this.angle);
    }
    else {
    c.rotate(this.angle);
    c.scale(-1,1);
    }
    c.translate(-this.x,-this.y);
    c.fillStyle = "#000000";
    c.rect(this.x, this.y, 2, 2);
    c.fill();
    c.restore();
    c.closePath();
  }; 

基本上在新的this.x和this.y中画了一个小点。

然而,实际上似乎发生的是每次点击时,子弹都会从玩家现在的任何地方重新绘制。这很难解释,但看看小提琴 - http://jsfiddle.net/Ey2eK/1/并在游戏区域点击几次,你会看到(不要担心子弹只向一个方向发展,我会在以后再做)。

我想要的是子弹按照正常的子弹进行旅行,这样我最终可以杀死它们。

感谢您提供的任何帮助!我真的很困惑这个。

1 个答案:

答案 0 :(得分:3)

JSFiddle

主要问题是您没有在点击时实例化新的Bullet对象。你只是一遍又一遍地重新定义Bullet函数的值。

createBullet()应该更像:

function createBullet() {
  var bullet = new Bullet();
  playerBullets.push(bullet);
}

但是由于你将拥有每个项目符号的许多实例,你实际上可以用bulletDraw / bulletUpdate替换draw / update函数,并在forEach调用中调用它们。

function Bullet() {
    ....
    this.bulletUpdate = function() { ... }
    this.bulletDraw = function() { ... }
}

// bullet refers to the current bullet that you're iterating over.
playerBullets.forEach(function(bullet) {
    if (bullet.x > WIDTH || bullet.x < 0 || bullet.y > HEIGHT || bullet.y < 0) { 
        bullet.active = false;
    }
    playerBullets = playerBullets.filter(function(bullet) {
        return bullet.active;
    });

    bullet.bulletUpdate();
    bullet.bulletDraw();
});