0

I'm just trying to create a very simple game with HTML5 and JS, now at the moment I have a ship that can fire a bullet. If you hold the spare bar the bullet is moved correctly and works fine. But if you press space bar in the middle of a shot, it will create a new bullet but the speed will be like doubled. Here is the code

function Bullet(x,y)
{
this.xPos = x; 
this.yPos = y; 
this.speed = 5; 
this.alive = true;
this.lifeTimer = 0;
}

tempBullet = new Bullet( -100, -100);
bullets[0] = tempBullet;

if (32 in keysDown && player.fired == false) //space
{ 
    //Create new bullet
    var bulletDone = false;
    player.fired = true;
    player.firedTimer = 1;
    tempBullet = new Bullet( player.xPos + 14, player.yPos);
    for( i = 0; i < bullets.length; i++ )
    {
        if( bullets[i].alive == false )
        {
            bulletDone = true;
            bullets[i] = tempBullet;
        }
    }

    if( bulletDone == false )
    {
        bullets[bullets.length] = tempBullet;
    }
}

if( player.firedTimer >= 1 )
{
    player.firedTimer++;
}

if( player.firedTimer >= 60 )
{
    player.firedTimer = 0;
    player.fired = false;
}

These are code snippets, the rest is stuff that would just get in the way. Am I re-using the old assets in my bullets array wrongly?

Cheers for the help and read

4

1 回答 1

1
tempBullet = new Bullet( player.xPos + 14, player.yPos);

请使用局部变量,您似乎忘记声明. var tempBullet虽然我猜不是你问题的原因。

for ( i = 0; i < bullets.length; i++ )
    if( bullets[i].alive == false ) {
        bulletDone = true;
        bullets[i] = tempBullet;
    }

请注意,在此循环中,您将所有死子弹重新分配给相同的 tempBullet. 这意味着当您遍历bullets集合以动画(移动)所有它们时,您将tempBullet多次访问。当你每次增加它的位置时,这将总结并导致不正常的速度。

要解决此问题,请在每次要替换死子弹时创建新的子弹对象:

var bulletDone = false;
for (var i = 0; i < bullets.length; i++ ) {
    if ( ! bullets[i].alive ) {
        bulletDone = true;
        bullets[i] = new Bullet( player.xPos + 14, player.yPos);
    }
}

if ( ! bulletDone ) {
    bullets.push( new Bullet( player.xPos + 14, player.yPos) );
}
于 2013-07-25T00:27:34.387 回答