How do I overwrite a delay in TweenMax? - actionscript-3

I am working in actionscript 3 using a Greensock TweenMax timeline. I have a one page scroller with two buttons (back to the top, and stop/play button).
The scroller automatically plays onLoad with a delay of 4 seconds. When I press stop/play button, it doesn't stop the delay. I have to wait the full four seconds before it functions. Also the 4 second delay only happens when the scroller runs for the first time. How can I get the 4 second delay to happen everytime the scroller repeats? How can I get the stop/play button to override the delay and play? I have worked on this for two days, and tried various techniques (for loops, timers, delayed calls, etc.) with no success. If anyone has ideas I will greatly appreciate it.
1) Code that starts the timeline:
myTween = new TweenMax(content_mc, 60, {delay:4, y:22, ease: Power0.easeNone, onComplete: restartFromTop });
2) This function controls the stop/play button
private function toggler(e:MouseEvent = null):void
{
if (playState == true){
toggleBtn.gotoAndStop(2);
myTween.pause();
playState = false;
trace("MC is now paused and stopped");
}
else if(playState == false) {
myTween.resume();
toggleBtn.gotoAndStop(1);
playState = true;
trace("MC is resumed from pause");
}
}
3) This function controls the restarting of the scroller when it repeats.
private function restartFromTop():void
{
myTween.restart()
playState = true;
}
4) This function controls the back to the top button
private function backToTop(event:MouseEvent):void
{
myTween.reverse();
if (playState == true){
myTween.restart();
myTween.resume();//stop animation
//toggleBtn.gotoAndStop(2);//changes button to pause
toggleBtn.buttonMode = true;
trace("page is scrolling");
}
if (playState == false){
myTween.restart();
myTween.pause();//stop animation
trace("play button is paused");
trace(timer);
}
//Adds a hand cursor on the button and adds a click event to the button.
toggleBtn.buttonMode = true;
toggleBtn.addEventListener(MouseEvent.CLICK, toggler);
}

I could not reproduce the first issue you are facing, that is the issue of delay with pause and resume. I tried a simple tween with 4 seconds delay and was able to pause and resume the tween without any delay.
For the other issue with restart, the TweenMax restart function takes a couple of arguments, and the first one being includeDelay:Boolean which is set to false by default. Setting this property to true fixes the issue.
Excerpt from the docs :
includeDelay:Boolean (default = false) — Determines whether or not the
delay (if any) is honored when restarting. For example, if a tween has
a delay of 1 second, like new TweenLite(mc, 2, {x:100, delay:1}); and
then later restart() is called, it will begin immediately, but
restart(true) will cause the delay to be honored so that it won't
begin for another 1 second.
Full docs can be found here
So, the following code should fix your restarting problem:
myTween.restart(true);
For your first issue, I would recommend you create a minimal scenario to reproduce it, and if it does, please do post a comment on my answer here.
Hope this helps. Cheers.

Related

AS3 - Make the screen flash for half a second

What I want to do is:
After colliding with an [object], I want the screen to flash for about half of a second. I have tried for loops and while loops but they seem to not work. I have no idea how I should program this.
I've been trying to figure out how to do this since I'v been making the game so it would be helpful if someone could help me.
Thank you for reading.
You need to use something that involves time. loops all run in a thread which doesn't pause for time - which is why they don't work.
Here is how you could do this with an AS3 Timer (let's say this code runs right after you've determined there's been a collision)
function flashScreen():void {
var timer:Timer = new Timer(50, 10); //run the timer every 50 milliseconds, 10 times (eg the whole timer will run for half a second giving you a tick 10 times)
var flash:Shape = new Shape(); //a white rectangle to cover the whole screen.
flash.graphics.beginFill(0xFFFFFF);
flash.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight);
flash.visible = false;
stage.addChild(flash);
timer.addEventListener(TimerEvent.TIMER, function(e:TimerEvent):void {
//we've told AS3 to run this every 50 milliseconds
flash.visible = !flash.visible; //toggle visibility
//if(Timer(e.currentTarget).currentCount % 2 == 0){ } //or you could use this as a fancy way to do something every other tick
});
timer.addEventListener(TimerEvent.TIMER_COMPLETE, function(e:TimerEvent):void {
//the timer has run 10 times, let's stop this flashing madness.
stage.removeChild(flash);
});
timer.start();
}
Other ways you can do this are with setInterval, setTimeout, a Tweening library,and an ENTER_FRAME event handler.

AS3 Button to stop Movieclip after its finished playing

Ok, so I'm a beginner at AS3 and Flash and I managed to put this code together for an animation. A Button called start_btn is supposed to start and stop a movieclip called main_mc. On the first click of the Button, the Movieclip is supposed to play (which it does), however on the second click, the movie stops in the middle of its animation (which I don't want). My question is, when you click the Button a second time, how can i get the Movieclip to finish playing its animation then stop on the last frame?
I thought about using if (main_mc.currentFrame == main_mc.totalFrames); {main_mc.stop(); but the Movieclip still does not stop on the last frame. The Movieclip itself also has a gotoAndPlay(2); command on the last frame so that the animation repeats before the Button is clicked a second time.
here is the code i have:
`start_btn.addEventListener(MouseEvent.CLICK, mainaniS);
function mainaniS(event:MouseEvent):void
{
main_mc.play();
start_btn.removeEventListener(MouseEvent.CLICK, mainaniS);
start_btn.addEventListener(MouseEvent.CLICK, mainaniSt);
}
function mainaniSt(event:MouseEvent):void
{
if (main_mc.currentFrame == main_mc.totalFrames);
{main_mc.stop();}
start_btn.removeEventListener(MouseEvent.CLICK, mainaniSt);
start_btn.addEventListener(MouseEvent.CLICK, mainaniS);
}`
Try main_mc.gotoAndStop(main_mc.totalFrames).
I was going to provide a quick and dirty solution, but decided instead to try and explain a few of the issues with your current implementation and attempt to refactor and explain and better one. Unfortunately I don't have access to Flash right now, so the code is untested.
You're adding and removing event listeners often, which is generally a bad idea. Instead, since you're using a single button to perform multiple functions it would make sense to track the button state in a separate variable. In this case, a boolean for whether or not the movieclip is currently playing.
var playing:Boolean;
Now we can combine the mainaniS and mainaniSt into one and perform a different action based on whether or not the movieclip is playing, and just keep the one eventlistener on the button. I've also taken the liberty of naming the method something more meaningful:
start_btn.addEventListener(MouseEvent.CLICK, onStartClick);
function onStartClick(event:MouseEvent):void
{
if(playing) {
playing = false;
}
else {
playing = true;
main_mc.play();
}
}
You may be wondering why we don't call main_mc.stop() in the first block: the reason is that you don't want to stop the movieclip as soon as you click the button, but after the movieclip has finished playing if the button has been clicked. Therefore, we just set playing to false to indicate that we want it to stop later.
Finally, we need to make sure the movieclip stops upon completion, but only if playing is false. To do this we add a listener to movieclip that is called every frame, and checks whether playing is false, and if it's on the last frame. Note that the last frame is actually totalFrames - 1: this is because the frame numbers start from zero rather than one (i.e. if totalFrames is 3, the frame numbers will be 0, 1, 2).
main_mc.addEventListener(Event.ENTER_FRAME, animate);
function animate(event:Event):void {
if(!playing && main_mc.currentFrame == main_mc.totalFrames - 1) {
main_mc.stop();
}
}
All the refactored code together:
var playing:Boolean;
start_btn.addEventListener(MouseEvent.CLICK, onStartClick);
main_mc.addEventListener(Event.ENTER_FRAME, animate);
function onStartClick(event:MouseEvent):void
{
if(playing) {
playing = false;
}
else {
playing = true;
main_mc.play();
}
}
function animate(event:Event):void {
if(!playing && main_mc.currentFrame == main_mc.totalFrames - 1) {
main_mc.stop();
}
}

Disabling button rollover for certain number of frames Flash actionscript 3.0

I'm constructing an area with selectable buttons that transition and appear every 10 frames. During these 10 frame transition periods I don't want the buttons to be selectable and if possible to disable the rollover.
I've tried creating an If statement on the addEventListener so that it only works when currentFrame is 11,21,31 etc but this didn't work. I then also tried the same principal on the function to which the Event Listener relates but still no success.
Does anyone have any ideas?
Add a listener for the ENTER_FRAME event, and put the if in the callback function.
For example
this.addEventListener (Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame (evt:Event):void {
if (currentFrame == 21) {
yourButton.enabled = false;
} else {
yourButton.enabled = true;
}
}
You could do 2 things:
1:
You manually add and remove the listener.
So when you start the transition, the listener is removed,
then when the transition ends, the listener is added.
2:
You make a custom listener which checks for the state of the frame to see whether it should execute its body.
EXAMPLE:
public void listener(event:Event) {
if (event.getSource().stage.getCurrentFrame() == 10) {//This is an example, I don't know whether this specific way will work.
//Run your code here
}
}

Having difficulty in understanding ActionScript 3 Timer class

I'm trying to make a dice game in Flash/ActioScript 3. I did all the essentials and it works smoothly. Now I want to improve the user experience. For instance, when it's computer's turn (to roll and do things according to die value) I want to animate the die. The die has 6 keyframes. So, for, say, 2 seconds the die will loop those 6 frames then it will stop on a value (depending on random generator). Somehow I can't do it as I want. How can I write a function(s) so that when I say,
animateDice()
it will do nothing but just animate the dice for a specified interval?
Update:
var timer:Timer = new Timer(10, 50);
myButton.addEventListener(MouseEvent.CLICK, onClick);
timer.addEventListener(TimerEvent.TIMER, animateDice);
function onClick(event: Event):void {
timer.start();
}
function animateDice(event: Event):void {
dice.play();
}
For instance, I don't understand why the above code doesn't work properly. It does work properly on first click, but not there after.
Update 2: I guess I'm still having problems. How do I suspend the running code until the timer stops? (Yes there is a work around---putting timer handlers inside other timers, etc. Is there an easy way?
Maybe, this will help:
First we see the die rolling (and a message box informs the user that the game will decide whom starts). Then it's either Human's or Computer's turn. When it's computer's turn, first we see the rolling die again for, say, 1 second. Then it stops and and we see the outcome. I'm a beginner and I nay be missing something, but from what I see it seems that all these simple steps (just showing the die rolling for some time) means lots and lots of lines.
If I use a simple timer for die animation, the script continues and the whole show goes away.
The timer object has three properties:
delay, or how often the event should fire
repeatCount, or how many times the event should fire
currentCount, or how many times the timer's event has fired thus far
You are creating the timer with new Timer(10, 50), which sets delay to 10 and repeatCount to 50. This means that, once you call timer.start(), timer will fire TimerEvent.TIMER every 10 milliseconds. Each time it is fired, it adds 1 to currentCount. When currentCount is greater than or equal to repeatCount (50), it stops looping the timer.
Once your timer has stopped, if you call timer.start() again, it will only fire the event once, because currentCount has not been reset to zero, and is still >= repeatCount.
If you call timer.reset() before calling timer.start(), it will set this value to zero and things should behave as expected.
var timer:Timer = new Timer(2000, 1);
myButton.addEventListener(MouseEvent.CLICK, onClick);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
function onClick(event: Event):void {
timer.reset();
timer.start();
dice.play();
}
function onTimerComplete(event:TimerEvent):void {
var roll:int = int(Math.floor(Math.rand()*6))+1;
dice.gotoAndStop(roll);
}
The timer is set to run only once, for 2000 milliseconds (which are 2 seconds). When Click occurs, the timer is reset (so that if it's not the first time it was clicked, it will run as if it was the first time) and started, and the animation starts a well. After 2 seconds, TIMER_COMPLETE will be fired by the timer, and we catch it and determine a final number for the die, then gotoAndStop to that frame.
I didn't try to compile the code, but the gist of it should work for you.
P.S, dice is the plural of 'die' :) you're skipping a great opportunity for the type of variable names we all want to use but can't!
You could try something a little more like this:
var t:Timer = new Timer(10, 50);
t.addEventListener(TimerEvent.TIMER, timerHandler);
t.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
t.start();
function timerHandler(e:TimerEvent):void {
gotoRandomFrame();
}
private function timerCompleteHandler(e:TimerEvent):void {
var finalNum:int = gotoRandomFrame();
// Using finalNum
}
private function gotoRandomFrame():int {
var num:int = Math.floor(Math.random() * 6) +1;
dice.gotoAndStop(num);
return num;
}
So use gotoAndStop to set your frame rather than using play

Fake mouseclick on hover AS3

This morning I stumbled to this question:
When hovering a button, is it possible to click it automatically after X seconds? So the user doesn't need to click it with his mouse?
How can I let Flash believe my mouse really clicked some button on the stage or brought up with as3?
I have a lot of buttons in my movie. So I prefer to use some code which will cover this function for all existing or coming up buttons in my movie.
I would normally use a code like this but is there some workaround to accomplish this in a different way? I do no want to add code to every button.
this.addEventListener(MouseEvent.OVER, onMouseClickEvent);
public function onMouseClickEvent(event:Event)
{
trace(event);
if(event.buttonDown) // if button goes down normally
trace("MOUSE CLICKED NORMALLY");
else
trace("left button was not down");
}
The easiest way i think, is to subclass Button.
Then you should add mouse over/out listeners, add click listener that looks like that
:public function clickListener(event:MouseEvent = null){...}
When the mouse is hovering, raise a flag that the mouse is on the object, start a timer and when the timer callback function is called, you check the if the flag (you turn the flag down, when the mouse is out) is true and just call clickListener()
Listen for MouseEvent.MOUSE_OVER and start a timer, at the end of which the button will send the MouseEvent.CLICK event. In the mouseover handler, use the SystemManager to add a listener for MouseEvent.MOUSE_OUT which cancels the timer. The timer removes the listener using the SystemManager as well. So does clicking the button.
Finally! Solved!
This did the trick:
public function runOnce(event:TimerEvent):void {
btnSignal.dispatch("KEYBOARD", btnCode);
}
Robusto & Radoslav Georgiev: Thank you for pointing the right direction!
(I'm answering this a little late but would like to give input for future people).
One way to 'skin this cat' is to simply let your hover event trigger a timer (i.e. 3 seconds). In an EnterFrame or other function let a number or Boolean change when 3 seconds is reached.
//Pseudo code
if(timer == 3)
{ numberVar = 1;
//or
BooleanVar = True;
}
else
{
numberVar = 0;
//or
BooleanVar = false;
}
//end
Then just as you connected your methods to a mouseEvent, connect those same methods to fire when numberVar == 1 or BooleanVar == True. That's it.
For super simplicity and readability let your MouseClickEvent just be numberVar = 1 or BooleanVar = True.
These become super simple to implement over time and in my experience are 'very' error proof. Easy to fix also in the case of a typo or something else. No super elusive imports either. Hope that helped.
Great question by the way (+ 1)
:D