How can we reset the repeatCount property while the timer is running - actionscript-3

How can we reset the repeatCount property while the timer is running.
In a game a countdown timer starts running at 120. If the user clicks on "hint" button i need to reduce the time by 5 seconds and start displaying the countdown
Now the problem is the countdown timer is reduced by five but the Timer runs till "-n*5".
"n" being the number of times hint button clicked.
How to solve this issue?

Here's one approach to your problem. Maintain a timer count separate from the Timer's repeatCount, and stop when that separate counter hits 0, instead of when the TimerComplete event occurs.
public var t:Timer;
public var count:int = 120;
protected function init(event:FlexEvent):void
{
t = new Timer(1000,count);
t.addEventListener(TimerEvent.TIMER, onTimer);
t.start();
}
protected function onTimer(evt:TimerEvent):void
{
count--;
//display count as time remaining
if (count <= 0)
{
//out of time!
t.stop();
}
}
protected function onHint(evt:MouseEvent):void
{
count-=5;
//update time or wait for next tick
}

Related

Actionscript 3 Control Timeline after Duration of no input from user

can anyone help me with this. I know its something very basic, but I just cant work it out.
What I need is for the timeline gotoandstop at frame 1 after 15 seconds of inactivity.
Basically this is for a directory board so if no one is using it, it will return back to the home screen after a period of inactivity.
Any help would be greatly appreciated.
Thankyou
What you can do, is use a Timer object. Then, whenever the user moves the mouse or clicks or presses a key, reset that timer back to 15 seconds.
On your frame 1, make a timer object:
//create the timer object var
var resetTimer:Timer;
//if it doesn't exist yet, create a new timer object and assign it to that var
if(!resetTimer){
resetTimer = new Timer(15000,1); //tick 1 time with a delay of 15
//listen for the TIMER event (fires when the delay is up)
resetTimer.addEventListener(TimerEvent.TIMER, reset);seconds
}else{
resetTimer.reset(); //if it did previously exist, stop/reset it (for when you revisit frame 1)
}
//go back to the first frame if the timer fires
function reset(e:Event = null):void {
resetTimer.reset(); //reset the timer
gotoAndStop(1); //go to frame 1
}
//LISTEN for various user input type events on stage (globally)
stage.addEventListener(MouseEvent.MOUSE_DOWN, userInput);
stage.addEventListener(MouseEvent.MOUSE_MOVE, userInput);
stage.addEventListener(KeyboardEvent.KEY_DOWN, userInput);
stage.addEventListener(KeyboardEvent.KEY_UP, userInput);
//if there was user input, reset the timer and start it again
function userInput(e:Event = null):void {
resetTimer.reset();
resetTimer.start();
}
The only thing left to do is, when you leave frame 1 and want the timeout to be applicable call resetTimer.start(). Presumably that would be on frame 2.
its possible to simulate it so:
class test extends MovieClip{
public var myTimer:Number;
public var input:TextField;
function test(){
myTimer=0;
input=new TextField();
this.addChild(input);
this.addEventListener(Event.ENTER_FRAME,timer);
input.addEventListener(Event.CHANGE, input_from_user);
}
function timer(ev){
myTimer +=(1/25);//if the frame rate is 25 frame per sconde
if(myTimer ==15){
this.gotoAndStop(1);
this.removeEventListener(Event.ENTER_FRAME,timer);
}
}
function input_from_user(ev){
myTimer =0;
}
}

Problems with adding and subtracting time from/to Timers

Now I am also using a timer in frame 8, which is my Gamescreen frame to try and create an energy bar, so decreasing by 1 every second, and everytime the character collides with an object then increment the value of count by 1 (which in my min is 1sec, right?), however the timer runs out prematurely, when the label is showing 3secs left after collecting 3 items the timer automatically ends, HELP ME! :)
var count:Number = 5; (temporary value for testing)
var theTimer:Timer = new Timer(1000, count);
theTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
theTimer.start();
function whenTimerComplete(e:TimerEvent):void
{
theTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, whenTimerComplete); //Remove listener
gotoAndStop("frameFive"); // Advance to score screen.
}
theTimer.addEventListener(TimerEvent.TIMER, theCountdown);
function theCountdown(e:TimerEvent):void
{
count--;
timerLabel.text = count.toString()
}
//Start the timer and show in the label.
timerLabel.text=count.toString();
theTimer.start();
All help and a solution is VERY much appreciated.
Here's an example countdown timer:
Launch Flash example
FLA source code
Countdown Timer AS3 source code
CS6 ZIP of source code
CS5 ZIP of source code
Create a countdown timer class at the root of your FLA:
CountdownTimer.as
package {
import flash.events.TimerEvent;
import flash.utils.Timer;
public class CountdownTimer extends Timer {
public var time:Number = 0;
public function CountdownTimer(time:Number = Number.NEGATIVE_INFINITY, delay:Number = 1000) {
super(delay, repeatCount);
if (!isNaN(time))
this.time = time;
repeatCount = Math.ceil(time / delay);
addEventListener(TimerEvent.TIMER, timerHandler);
}
protected function timerHandler(event:TimerEvent):void {
time -= delay;
if (time == 0)
dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
}
public function dispose():void {
removeEventListener(TimerEvent.TIMER, timerHandler);
}
}
}
On the timeline of your FLA, create a timer with the total number of milliseconds to countdown:
var timer:CountdownTimer = new CountdownTimer(60000);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
timer.start();
In the example above, the timer will countdown for 1-minute (60-seconds). Each second the timerHandler will be called. When it reaches 0, the timerCompleteHandler will be called.
function timerHandler(event:TimerEvent):void {
timerText.text = (timer.time / 1000).toString();
}
function timerCompleteHandler(event:TimerEvent):void {
timerText.text = "COMPLETE";
}
To add time to the timer, add milliseconds to time. If you want the timer to dispatch timer complete event when it reaches 0, update the repeatCount:
timer.time += 1000;
timer.repeatCount += 1;
Likewise to remove time from the timer, subtract milliseconds from time; and again, if you want the timer to dispatch timer complete event when it reaches 0, update the repeatCount:
timer.time -= 1000;
timer.repeatCount -= 1;

Actionscript 3 Timer on click hold

I have a function where I need to click and cube once and the cube will rotate to that side, then when i click and hold for 2 seconds will go to fifth page or when i click with no hold will start the cube rotating.
This is what I have
var numPressed:Number = 0
function side6(event:MouseEvent):void {
numPressed++;
if (numPressed % 2) {
SimpleZSorter.sortClips(container);
TweenLite.to(container, 1, {rotationX:-8,rotationY:193});
addEventListener(Event.ENTER_FRAME, rotateStop);
removeEventListener(Event.ENTER_FRAME, rotateThis);
}else if (NEED SOEMTHING HERE TO DETECT MOSUE HOLD AFTER SECONDS) {
gotoAndStop(5);
}
else{
addEventListener(Event.ENTER_FRAME, rotateThis);
}
}
The idea atm is numpressed calculates if the presses are odd or even, meaning 1 click will stop the cube rotating, 2 will start it again, a third will stop if and so forth, i need this to keep acting like that.
I need something in the second if statement, everything works well apart from getting it to work on holding the mouse.
Any help appreciated
Ian
I would suggest using MouseEvent.DOWN and MouseEvent.UP and store Date.time for this.
EG: This set of functions would track the ammount of millisenconds elapsed between the MouseEvent.DOWN and the MouseEvent.UP event.
private var mouseDownTime:Number = NaN,mouseUpTime:Number = NaN;
private function init():void
{
yourCubeObject.addEventListener(MouseEvent.DOWN,onMouseDown);
yourCubeObject.addEventListener(MouseEvent.UP,onMouseUp);
yourCubeObject.addEventListener(MouseEvent.OUT,onMouseOut);
}
private function onMouseOut(event:MouseEvent):void
{
mouseDownTime = mouseUpTime = NaN;//clear storage
}
private function onMouseDown(event:MouseEvent):void
{
mouseDownTime = new Date().time;//store system time in milliseconds since epoc
}
private function onMouseUp(event:MouseEvent):void
{
mouseUpTime = new Date().time;
if (!isNaN(mouseDownTime))//avoid error case where mouse went down outside object
{
if ((mouseUpTime - mouseDownTime) >= 2000)
{
//mouse held down for more the 2 seconds, your function here.
}
}
onMouseOut(event);//reset counters
}

Timer AI not working

var moveTimer:Timer = new Timer(1);
moveTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void
{
//code
}
moveTimer.start();
moveTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone)
function timerDone(e:TimerEvent):void
{
upKey = false;
}
Hey Guys, so this is my code. I have some very simplistic AI in my game and I'm trying to utilize a timer in order for the enemy to move forward for about 2-3 seconds and then stop. To do this I'm using the variable upKey as a boolean which is set to true, but when the timer finishes it gets set to false and upon it being set to false, there is an if statement that will reduce the enemy's speed to 0.
This is my first time using a timer and the enemies dont really stop... they kind of just keep going until they wander off the screen. Am I doing this correctly or is it a problem elsewhere in my code? Also, is there a better more effiecient way to use a timer?
Thanks, James.
From the code you cite, the timer constructor does not specify repeatCount indicating it should repeat indefinitely. For the timerDone() handler to be called, you must specify a repeat count.
Also, note that a delay below 20-milliseconds is not recommended.
Timer constructor parameters: Timer(delay:Number, repeatCount:int = 0)
delay:Number — The delay between timer events, in milliseconds. A
delay lower than 20 milliseconds is not recommended. Timer frequency
is limited to 60 frames per second, meaning a delay lower than 16.6
milliseconds causes runtime problems.
repeatCount:int (default = 0) — Specifies the number of repetitions.
If zero, the timer repeats indefinitely, up to a maximum of 24.86 days
(int.MAX_VALUE + 1). If nonzero, the timer runs the specified number
of times and then stops.
Timers are not recommended for animated content. Instead, use Event.ENTER_FRAME to manipulate frame-based animation.
One approach would be to use timers to trigger state changes to your game model:
/** timer */
var timer:Timer;
/** whether enemies are advancing */
var advance:Boolean = false;
// start timer at 5-seconds intervals
timer = new Timer(5000);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.start();
// animation controlled by Event.ENTER_FRAME
addEventListener(Event.ENTER_FRAME, frameHandler);
In your timer handler, you can adjust the timer delay depending on the state of your game.
/** timer handler */
function timerHandler(event:TimerEvent):void
{
// stop the current timer
timer.stop();
// depending on the current enemy state
switch (advance)
{
// if true, stop advancing and wait 5-seconds
case true:
trace("Stop advancing, wait 5-seconds");
timer.delay = 5000;
break;
// if false, advance for 2-seconds
case false:
trace("Advance for next 2-seconds");
timer.delay = 2000;
break;
}
// invert advance state.
advance = !advance;
// restart timer
timer.start();
}
Likewise on enter frame, control animation of your enemy based on game state:
/** frame handler, advancing enemy if 'advance' is true */
function frameHandler(event:Event):void
{
if (advance) { /** move enemy forward */ }
}
This alternates state of your enemies, outputting:
Advance for next 2-seconds
Stop advancing, wait 5-seconds
Advance for next 2-seconds
Stop advancing, wait 5-seconds
Advance for next 2-seconds

Need help using a timer in Action Script 3

Alright, so I am fairly new to AS3 and I have a level in my game where you have to stay alive for 45 seconds. If I use a code like (Or if there is a better code, I'll use that one)
var myTimer:Timer = new Timer(1000, 1); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, runOnce);
myTimer.start();
function runOnce(event:TimerEvent):void {
trace("runOnce() called # " + getTimer() + " ms");
}
How can I use this to make my game move to scene 6 if they stay alive for 45 seconds? I also want to display text on the animation that keeps track of how long they've been alive so they know how long they have left. How could I accomplish this?
private var startTime:int;
function startGame() {
// this is called when your game starts
startTime=getTimer();
... // rest of init code
}
function onEnterFrame(e:Event):void {
// main loop, whatever you need to do in here
currentTime=getTimer()-startTime; // here we receive the elapsed time
// pause handling is excluded from this example!!11
if (weAreDead()) {
survivalTime= currentTime;// here
...
} else if (currentTime>45000) {
//advance to scene 6 here
}
}
Set the listener for Event.ENTER_FRAME to onEnterFrame, start the game with setting the stored time, and pwn.
The simplest solution is to go ahead and use the timer, but set the value to 45000 and make sure to keep a reference of the timer or it will be garbage collected. Also, create a separate function which allows you to kill the timer from anywhere if this particular thing ever needs to just "go away" without completing.
public static const DELAY:int = 45;
private var _timer:Timer;
public function setTimer():void
{
_timer = new Timer( DELAY * 1000, 1 );
_timer.addEventListener( TimerEvent.TIMER_COMPLETE, timerCompleteHandler );
_timer.start();
}
private function timerCompleteHandler( event:TimerEvent ):void
{
disposeTimer();
goDoTheThingThatYouNeededToDo();
}
public function disposeTimer():void
{
_timer.stop();
_timer.removeEventListener( TimerEvent.TIMER_COMPLETE, timerCompleteHandler );
_timer = null;
}