Jump to content

Problem with timers


Bonsaiheldin
 Share

Recommended Posts

Hey!

I want the weapons of a spaceship to shoot in volleys / bursts, meaning it should fire some bullets with a delay in between, reload and then repeat. I'm trying to accomplish this with simple repeat timers:

// Slightly modified code
fire = function()
{
    for (var i = 0; i < weapons.length; i++)
    {
        var weapon = weapons[ i ];

        if (game.time.now >= weapon.next)
        {
            // Reset reload delay (1000ms)
            weapon.next = game.time.now + weapon.rate;

            // Shoot 5 bullets with 100ms duration between
            game.time.events.repeat(100, 5, function()
            {
                new Bullet(game,
                {
                    x: weapon.world.x,
                    y: weapon.world.y,
                    angle: ship.rotation
                });
            }, game);
        }
    }
}


My problem is that, for some odd reason, all bullets shoot from the same weapon. The timer always takes the x, y and angle values of the last given element, no matter if i iterate the weapons with a loop or do it manually for each. Even random values don't work.

Any idea? It makes no sense to me :ph34r:

Link to comment
Share on other sites

So you are saying that all bullets fire from the last weapon in your weapons array, no matter how you iterate through the weapons array. Correct?

You also say that random values don't work. Does that mean that if you write:

new Bullet(game,
  {
    x: Math.floor(Math.random() * game.world.width),
    y: Math.floor(Math.random() * game.world.height),
    angle: Math.random() * 2 * Math.PI
  });

the bullets will still all spawn from the same location?

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...