How do I stop a timed event from happening? - actionscript-3

I am making a game where a user clicks on insects and tries to get a good high score. When the user clicks on one insect, the insect plays an animation and stays in its spot for 2 seconds in this code:
import flash.events.MouseEvent;
import flash.display.MovieClip;
import fl.motion.Animator;
import flash.events.*;
play();
var mysound:squish = new squish();
this.addEventListener(MouseEvent.CLICK, kill);
this.dead = false;
function kill(e:MouseEvent):void
{
this.dead=true;
mouseChildren=false
mysound.play();
gotoAndPlay(21);
this.removeEventListener(MouseEvent.CLICK, kill);
flash.utils.setTimeout(removeSelf,2000);
}
function removeSelf():void
{
this.parent.removeChild(this);
}
When the user pauses the game, the enemies are stopped and they turn invisible. The only problem is that when the user clicks on the insects, and hits the pause button, the insects stay there for 2 seconds. How do I remove the timer when the person pauses the game so that no insects are on the screen?

A few tips:
Never use timeouts, they will produce poor, unsustainable, hard to debug code. Use Timer instead. Timer provides nice little features like: repeat times, pausing, resuming and resetting the timer. So you could set the timers timeout to 2000ms, repeat once and set an event listener TimerEvent.TIMER_COMPLETE to remove the insect etc. You can pause the timer when you pause the game and resume when needed.
If you do however use timeouts, assign a uint to it and use a clearTimeout() method to stop it.
construction such as this.parent.removeChild(this); is ugly. Instead, dispatch an event as an alternative and let the parent to manage the dead bugs (remove from arrays, display list etc).
Storing a sound in every bugs instance will take way more memory than needed. Make a static sound library class and call the play() method from it.

Related

Flash AS3 | Looping sound for each animation set

with University done I've finally had time to go back to practicing my Flash work, and I need some help with getting sound to loop and change depending on what part of the animation is playing.
This is also partly a follow up question to an older one I asked, so look here to get more detail as to where I'm coming from if you don't understand! (I've solved that issue, the current one relates to following up on it!)
Flash AS3 | Finishing current animation set before code is executed
The situation is basic: I have two different scenes, one of a man walking and one of a man running. It loops seamlessly of the man walking until you hit a button, where it finishes the animation then starts looping the run animation. Likewise, hitting the button again, finishes the loop before going back to the looping walk animation. The code for the button is below.
import flash.events.MouseEvent;
Next2.addEventListener(MouseEvent.CLICK, Change_2);
function Change_2(event: MouseEvent): void
{
addEventListener(Event.ENTER_FRAME, enterFrame);
function enterFrame(e:Event):void {
if (currentFrame == 30) {
gotoAndPlay(31);
removeEventListener(Event.ENTER_FRAME, enterFrame);
}
}
}
My issue is trying to get a footstep sound to match up with these animations. So while the man is walking, the 'walking footsteps' sound clip will play and loop alongside the animation, and when the button is pushed and the animation moves into the running animation, the 'running footsteps'' sound will play.
Any help on this would be much appreciated. I'm terrible when it comes to anything audio/code based.
Well u can check about soundChannel. soundChannel can stop() and play() ur audio.
So import ur external sound or use internal one. ur code probably seems like this.
var mySound:Sound = new Sound(new URLRequest("YourSoundPath"));
var sc:SoundChannel = new SoundChannel();
//when u wanna play
sc = mySound.play();
//when u wanna stop
sc = mySound.stop();
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/SoundChannel.html
also look this link for more info
If you want to really MATCH the footsteps to the animation (for example, the step sound should play when the player have put his feet down) the only sure way to do that is to place the sound on a different layer where your animation is and set the sound to play as "stream" (if i remember correctly).
Otherwise the animation might be out of sync because of different computer capabilities, current computer or graphics card load etc.
When the sound is set to play as "stream" the flash player is orienting on the sound and drop frames if the graphics are slow to keep the sound and animation in sync

Make the first tick of a timer instant(ignore the millisecond delay)

I have function where a series of buttons are created, tween for a second to their position in quick succession and then the timer that triggers the tween ends.
I experimented with the delay/time settings on the tween and couldn't get the desired effect without a timer class since I want each new button to begin it's tween before the previous one finishes.
I almost have it looking how I want now using a timer, but the delay at the start is still a problem. Is there a quick way to skip the delay for the first fire of the timer, or will I need to go the long route and create additional timer/tween/functions to simulate this effect?
One solution would be to just call the method without the whole timer thing. Take a look at this example:
// Here, we create the timer
var t:Timer = new Timer(200);
t.addEventListener(TimerEvent.TIMER, onTimer);
Let's say that some event happened, like a button press. Upon pressing the button a space-ship in a game starts to shoot, but you want the first bullet to fly out right away, and not wait for the 200ms delay:
t.start(); // make sure t is a class member, not a local variable
shoot();
This way the timer will start, but the first action will happen right away ;)
Just for clarity, the timer handler could look something like this:
private function onTimer(e:TimerEvent):void
{
shoot();
}
As you see, there is no need to put the implementation of shooting right into the handler function to preserve it's re-usability and better maintainability.
Simply as a cool thing to know, you can actually change the delay of your timer on run-time.
Here's a small example:
// Creating the timer with 2 handlers
var t:Timer = new Timer(200);
t.addEventListener(TimerEvent.TIMER, onTimerSetNewDelay);
t.addEventListener(TimerEvent.TIMER, onTimer);
t.start();
The implementation of onTimer() doesn't matter, but onTimerSetNewDelay can be interesting:
private function onTimerSetNewDelay(e:TimerEvent):void
{
t.delay = YOUR_NEW_DELAY_VALUE;
t.removeEventListener(TimerEvent.TIMER, onTimerSetNewDelay); // removing the listener so it doesn't set the same delay over and over again.
}
what about calling the function using onTimer(null);?

How to code a play and pause button in flash AS3

I have made a simple game in flash. It includes a timer, falling objects and an object controlled by using swipe. So is there a way to stop every activity with the pause button and start it back again with the play button. Basically I want the whole stage to pause and play using buttons.
There is no way to do it automaticaly. You could base your entire game on a timer (even for animations and physics) and pause this timer. But this is a feature you have to think about during the very design of your game. Now I guess you just have to pause every movieclip, cancel your listeners to ENTER_FRAME and pause your timer.
Many game engines such as Flixel or FlashPunk include this feature
The way I do this in as3 is to run two timers, one that always runs at about 500ms and another that runs at framerate that varies with the speed of the game. Something like
public var speedControl:int = 15;
public var tick:Timer;
public function timers():void{
tick = new Timer(1000/speedControl);
tick.addEventListener(TimerEvent:TIMER,tickd);
tick.start();
}
public function tickd(t:TimerEvent):void{
// the timer has ticked
}
public function pause():void{
tick.stop();
}
public function play():void{
tick.start();
}
This is a basic example of course created on the fly, but you can call the pause or play button with a standard event listener. If your whole stage runs off of the timer, it will all stop. I use a second timer however that doesnt get stopped and started with the functions also. You really do want some things to run all the time.
If you wouldn't mind using the FP 11.8 Beta, it has that feature nativly to stop all movieclips recursively. Check it out here:
http://labs.adobe.com/technologies/flashruntimes/flashplayer/

AS3 Game loop and draw frame

I am building a game for school in AS3. I made a game loop with a timer so this game can run faster.
private var updateTimer:Timer;
updateTimer = new Timer(0);
updateTimer.addEventListener(TimerEvent.TIMER, update);
updateTimer.start();
private function update(e:TimerEvent):void { }
This is working, but my teacher did show me a function/command how I can draw/render a frame.
Because of that the frame rate will go up. Unfortunately, I lost that code and I ca'nt find that function anywhere. Does anyone know that function? Yes, I know this way is very unstable.
Thanks a lot.
Are you thinking of TimerEvent.updateAfterEvent()? This causes Flash to render a new frame immediately independent of the movie frame rate in response to a timer or mouse event.
e.updateAfterEvent();
If you want to just change the frame rate of a game without messing with timers, you can always use stage.frameRate and go from there. So if you want to increase the frame rate, just use stage.frameRate++;.

Smooth scrolling on Flash AS3

Is it possible to do completely smooth scrolling in Flash (ActionScript 3)? In the following test I am creating a bitmap consisting of random noise, then moving it to the left periodically. I have no heavy tasks running in the background. What I am looking for is smoothness that would be on par with my Amiga 500 from 1987 :-)
package {
import flash.display.*;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Game extends Sprite {
var noiseBitmap;
public function Game() {
var noiseBitmapData = new BitmapData(stage.stageWidth * 3, stage.stageHeight);
noiseBitmapData.noise(0, 0, 255, 7, true);
noiseBitmap = new Bitmap(noiseBitmapData);
addChild(noiseBitmap);
var t = new Timer(1000/30, 999999);
t.addEventListener("timer", function (e:TimerEvent) {
noiseBitmap.x--;
});
t.start();
}
}
}
The "rendering code" takes <1 millisecond to run on my computer (2.4 GHz Mac), but still the movement will occasionally get stuck for a frame or two, making the movement appear jerky.
FPS is set to 30 in Flash. I have tried running it both using "test movie" and in the browser (Chrome). Target is Flash Player 11.2. I have also tried calling e.updateAfterEvent() to force a redraw. I have Also played around setting the delay and FPS to slightly different values, but no improvement.
This is different from not smooth scrolling in AS3 because I am already using a BitmapData. Also I have tried using the ENTER_FRAME event instead of a timer as suggested in a reply to that question, but it did not help.
When using a timer, you will not be exactly synced with the frame rate. As you mention, the frame rate fluctuates a little making your timer sometimes fire twice during one frame or skipping a frame. To be sure to be more in sync with the frame rate, you should listen to the Event.ENTER_FRAME event.
An example:
this.addEventListener(Event.ENTER_FRAME, updateFrame);
⋮
function updateFrame(e:Event):void {
noiseBitmap.x--;
}
I suggest you try out Greensock's TweenLite. It is a highly optimized engine to do all sorts of tweening through code and is available for AS2 and AS3. You can find it here.
Walkietokyo's solution is still frame based and would not eliminate the issues you run into. Instead use time-based animation (which TweenLite actually implements). For more info refer to this article.