0

I'm making a side scrolling game in as3, where the player spawns units which automatically walks towards the exit on the other side of the screen, but there are towers stopping them. I would like the towers to shoot separately, is there any way? Here's my code, once the if statements are satisfied all towers fire at the same time.

    private function tower1Fire():void 
    {
            for (var j:int = creep1Array.length - 1; j >= 0; j--)
            {
                for each (var towerOne:mcTower1 in tower1Array)
                {
                    if (creep1Array[j].x - towerOne.x <= 100 && creep1Array[j].y > towerOne.y)
                    {
                        var newTower1Bullet:mcLaser1 = new mcLaser1;
                        newTower1Bullet.x = towerOne.x;
                        newTower1Bullet.y = towerOne.y;
                        tower1BulletArray.push(newTower1Bullet);
                        stage.addChild(newTower1Bullet);
                    }
                }
            }
    }

I have 3 towers on the screen, added using this code:

             var tower1New1:MovieClip = new mcTower1;
        tower1New1.x = 313;
        tower1New1.y = 340;
        tower1Array.push(tower1New1);
        MovieClip(root).addChild(tower1New1);

I don't get any error. Any reply will be appreciated, thanks!

1 Answers1

1

From what I can tell, all of your towers are going to 'fire' in a single 'frame render', which is why it looks like they are all firing at once. (because your whole loop is going to execute within a single draw operation)

If I we're you, I would listen to the ENTER_FRAME event, and keep a count of the frames.... I would fire a single tower only, once very 10-20 frames. So...

private ENTER_FRAME(event:Event):void
{

    if(frameCount >= 20)
    {
        // TODO: fire logic goes here

        // reset the frameCount to zero
        frameCount = 0;

        // you need to keep a running index of your towers, 
        // so the next time your code executes, it will fire the next tower
        towerIndex++
    }
    frameCount++;
}

So, if you we're to do it that way, you wouldn't have a for loop.

  • Hi, thanks for the reply. The problem right now is that I want the towers to only fire when there are creeps nearby, and right now, if a creep is nearby a tower, ALL the towers will fire. I can't add an 'if' statement in the code you just wrote, right? I'm sorry I'm still pretty new to as3... – user2036822 May 21 '13 at 17:42
  • Yeah you can, so where I added the "fire logic goes here" you could check if there are any creeps nearby. Sorry I didnt quite understand the first time... so you will also probably only want to increment the towerindex within your if statement. – Kaushal De Silva May 22 '13 at 01:11