setting up a timer in flash as3

14,807

So you want a timer that ticks every 15 seconds for 60 seconds. That means it will have to tick 4 times (60 / 15). Let's call it speedTimer; You have to instantiate it something like that:

speedTimer = new Timer(60 * 1000, 4);

Then you need to add two different event listeners. One that will be called every time your timer ticks, and one that will be called when it stops.

speedTimer.addEventListener(TimerEvent.TIMER, onSpeedTimer);
speedTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onSpeedTimerComplete);

In the first event handler you increment the value of speed. For that to be possible you need to change it from a constant to a variable.

In the second handler, you put your code to go to another page.

There is several points that ought to be mentioned:

When you declare a variable, you should specify a scope (i.e. private, public, etc.) the same way you do for your functions:

private var catcher:Catcher;

When you declare a function, you should specify a return value, except for the constructor of your class. If the function returns nothing, you can use void:

public function setNextObject():void {
    [...]
}

Naming is important, especially to understand your code when you'll read it later. If you use a Timer it is better to name it something like myTimer rather than nextObject.

This is the same for function names: setNextObject() creates a new Timer and starts it, so I would name it startTimer().

When you create a new timer like this:

new Timer(1000 + Math.random() * 1000, 1);

You specify a repeat count of 1. That means that your timer will stop after the delay is met. Because you want it to run over and over again, your should instead specify a repeatCount of 0 (infinite). To keep the functionnality that your timer tick at random interval, you'll then need to set a new delai value in your event handler

myTimer.delay = 1000 + Math.random() * 1000;

goodObjects and nadObjects are never modified, so you should extract them in constants:

private const GOOD_OBJECTS:Array = ["Circle1","Circle2"];
private const BAD_OBJECTS:Array  = ["Square1","Square2"];

With all these changes, it should now be easier to understand what your code is doing. Here is the updated code:

package
{
    import flash.display.*;
    import flash.events.*;
    import flash.text.*;
    import flash.utils.Timer;
    import flash.utils.getDefinitionByName;

    public class CatchingGame extends MovieClip
    {
        private const GOOD_OBJECTS:Array = ["Circle1","Circle2"];
        private const BAD_OBJECTS:Array = ["Square1","Square2"];

        private var catcher:Catcher;
        private var myTimer:Timer;
        private var speedTimer:Timer;
        private var objects:Array = new Array();
        private var score:int = 0;
        private var speed:Number;

        public function CatchingGame()
        {
            speed = 7.0;
            catcher = new Catcher();
            catcher.y = 350;
            addChild(catcher);
            startTimer();
            startSpeedTimer();
            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        public function startTimer():void
        {
            myTimer = new Timer(1000 + Math.random() * 1000, 0);
            myTimer.addEventListener(TimerEvent.TIMER, onTimer);
            myTimer.start();
        }

        public function startSpeedTimer():void
        {
            speedTimer = new Timer(60 * 1000, 4);
            speedTimer.addEventListener(TimerEvent.TIMER, onSpeedTimer);
            speedTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onSpeedTimerComplete);
            speedTimer.start();
        }

        public function onTimer(e:Event):void
        {
            myTimer.delay = 1000 + Math.random() * 1000;
            if (Math.random() < .5)
            {
                var r:int = Math.floor(Math.random() * GOOD_OBJECTS.length);
                var classRef:Class = getDefinitionByName(GOOD_OBJECTS[r]) as Class;
                var newObject:MovieClip = new classRef(); 
                newObject.typestr = "good";
            }
            else
            {
                r = Math.floor(Math.random() * BAD_OBJECTS.length);
                classRef = getDefinitionByName(BAD_OBJECTS[r]) as Class;
                newObject = new classRef(); 
                newObject.typestr = "bad";
            }
            newObject.x = Math.random() * 500;
            addChild(newObject);
            objects.push(newObject);
            startTimer();
        }

        private function onSpeedTimer(e:Event):void
        {
            speed++;
        }

        private function onSpeedTimerComplete(e:Event):void
        {
            // Go to some page...
        }

        public function onEnterFrame(e:Event):void
        {
            moveObjects2();
        }

        public function moveObjects2():void {
            for(var i:int = objects.length - 1; i >= 0; i--)
            {
                objects[i].y += speed;
                if (objects[i].y > 400)
                {
                    removeChild(objects[i]);
                    objects.splice(i, 1);
                }
                if (objects[i].hitTestObject(catcher))
                {
                    if (objects[i].typestr == "good")
                    {
                        score += 5;
                    }
                    else
                    {
                        score -= 1;
                    }
                    if (score < 0)
                    {
                        score = 0;
                    }
                    scoreDisplay.text = "Score: "+score;
                    removeChild(objects[i]);
                    objects.splice(i,1);
                }
            }
            catcher.x = mouseX;
        }
    }
}

If there is still some part that you do not understand, please feel free to mention them in comment

Share:
14,807
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a project due in a weeks time, and I have almost completed it. I have got one more issue I need to work out and I am stumped.

    I will paste the code I have so far below.

    If you could also explain what the code is doing so I know what it's doing if it's not too much trouble, the code was taken from an in class activity and I changed the identifiers to match what my graphics are called. I am trying to implement a timer in my drop and catch game that every 15 seconds, it increases the speed of the falling objects. The timer will start from 60 seconds, and when it hits 0 seconds, it should go onto a separate page.

    Could someone please explain how I would do this? I am not that good at understanding the code in flash, so if you could keep it as simple as possible I would be greatly appreciative.

    The code that I have is as follows. It works perfectly, I just need to change a section to the timer :

    package {
    import flash.display.*;
    import flash.events.*;
    import flash.text.*;
    import flash.utils.Timer;
    import flash.utils.getDefinitionByName;
    
    public class CatchingGame extends MovieClip {
        var catcher:Catcher;
        var nextObject:Timer;
        var objects:Array = new Array();
        var score:int = 0;
        const speed:Number = 7.0;
    
        public function CatchingGame() {
            catcher = new Catcher();
            catcher.y = 350;
            addChild(catcher);
            setNextObject();
            addEventListener(Event.ENTER_FRAME, moveObjects);
        }
    
        public function setNextObject() {
            nextObject = new Timer(1000+Math.random()*1000,1);
            nextObject.addEventListener(TimerEvent.TIMER_COMPLETE,newObject);
            nextObject.start();
        }
    
        public function newObject(e:Event) {
            var goodObjects:Array = ["Circle1","Circle2"];
            var badObjects:Array = ["Square1","Square2"];
            if (Math.random() < .5) {
                var r:int = Math.floor(Math.random()*goodObjects.length);
                var classRef:Class = getDefinitionByName(goodObjects[r]) as Class;
                var newObject:MovieClip = new classRef(); 
                newObject.typestr = "good";
            } else {
                r = Math.floor(Math.random()*badObjects.length);
                classRef = getDefinitionByName(badObjects[r]) as Class;
                newObject = new classRef(); 
                newObject.typestr = "bad";
            }
            newObject.x = Math.random()*500;
            addChild(newObject);
            objects.push(newObject);
            setNextObject();
        }
    
        public function moveObjects(e:Event) {
            for(var i:int=objects.length-1;i>=0;i--) {
                objects[i].y += speed;
                if (objects[i].y > 400) {
                    removeChild(objects[i]);
                    objects.splice(i,1);
                }
                if (objects[i].hitTestObject(catcher)) {
                    if (objects[i].typestr == "good") {
                        score += 5;
                    } else {
                        score -= 1;
                    }
                    if (score < 0) score = 0;
                    scoreDisplay.text = "Score: "+score;
                    removeChild(objects[i]);
                    objects.splice(i,1);
                }
            }
    
            catcher.x = mouseX;
    
        }
    }
    }
    

    thank you for taking the time to read my issue and any help given

  • Admin
    Admin about 11 years
    thank you so much, this helped a lot :) i just need to implement a few small improvements that i realised and its done, once again, thank you :)
  • duTr
    duTr about 11 years
    You're welcome. Please consider accepting my answer if it answered your question
  • Admin
    Admin about 11 years
    i have yet another issue, my code is as follows, im trying to remove the objects from the stage to bring up a Promotion screen for the item that i am promoting for the project. (the issue i think is the second last piece of code in the code below
  • Admin
    Admin about 11 years
    i have implemented the code as above, but i have an issue where i am trying to remove all objects from the stage and move on to a promotion screen in my library, i have tried making the promotion screen a movie clip but that screws up the code i have. teh code that i have to move to the screen which isnt working is as below: //once score reaches past 100 if(score > 100) { var promotionScreen:promotion = new promotion; gotoAndStop("score") addChild(promotionScreen); } //end of if statement