Search code examples
actionscript-3flashactionscripttimerflash-cs6

Object and Timer AS3


I have a question about TIMER in AS3

i have a zombie object on my stage, i want him to come and attack the HERO.

what i want to do is:

  1. the zombie walks toward the hero
  2. When he is close enough to attack, he proceeds to attack.
  3. the problem : i want him to attack only ONCE every 5 seconds, so that the hero has a chance to hit him back. The problem is i am not familiar with timer, and i still couldn't find any tips / tuts / answers that would help me. I don't know where should I put the timer, in a new timer function or in my zombie function.

thank you :)

here's the code

if (zombie.x>hero.x+50)
{
    zombie.x-=5;
    zombie.scaleX=-1;

    if(zombie.x<hero.x+100){
        zombie.gotoAndStop("attack"); 
        //so that the zombie attacks when the hero is in range

    }
}

Solution

  • you can do something like this :

    var timer:Timer = new Timer(5000);//that's 5 second
    
    if (zombie.x>hero.x+50)
    {
        zombie.x-=5;
        zombie.scaleX=-1;
    
        if(zombie.x<hero.x+100){
            attack();
        }
    }
    
    function attack(  ) : void
    {
      // attack the first time
      zombie.gotoAndStop("attack"); 
    
     //than launch the timer
      timer.addEventListener(TimerEvent.TIMER, repeatAttack );
      timer.start();
    }
    
    //will be called every 5000 ms == 5 sec
    function repeatAttack ( event : TimerEvent ) : void
    {
     zombie.gotoAndStop("attack"); 
    }
    
    //if you want to stop the attack you can use this function for example
    
    function stopAttack() : void
    {
       timer.removeEventListener(TimerEvent.TIMER, repeatAttack );
       timer.stop();//stop timer
       timer.reset();//resetCount to zero   
    }
    

    I hope this will help you solve your issue