Canvas
Canvas

Reputation: 5897

Reusing an Array, but odd out come

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

Upvotes: 0

Views: 82

Answers (1)

Bergi
Bergi

Reputation: 664484

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

Please use local variables, you seem to have forgotten to declare the var tempBullet. Not the cause of you problem though I guess.

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

Notice that in this loop you are reassigning all dead bullets to the same tempBullet. That means when you iterating over the bullets collection to animate (move) all of them, you will visit the tempBullet multiple times. When you're increasing its position each time, this will sum up and result in the unnormal speed.

To fix that, create new bullet objects every time you want to replace a dead bullet:

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) );
}

Upvotes: 1

Related Questions