AS3 removing local enterFrame listener - actionscript-3

(I don't know why the question doesn't show the "hello")
Anyway, hello all,
I have this code:
myVideo1.addEventListener(MetadataEvent.METADATA_RECEIVED, timeListener);
function timeListener(eventObject:MetadataEvent):void
{
var totalSeconds = String(eventObject.info.duration);
durationTime = String(Math.floor(totalSeconds));
addEventListener(Event.ENTER_FRAME, updateTime2);//<---LISTENER
var timeFull = durationTime;
function updateTime2(event:Event):void
{
var elapsedSeconds = String(Math.floor(myVideo1.playheadTime));
var runTime:String = (elapsedSeconds);
var timeGone = Math.floor((eventObject.info.duration) - (myVideo1.playheadTime));
var timeRem = Math.floor(timeGone / 60);
var secGone = String(timeGone / 60 - timeRem);
// etc...
}
}
This piece of code gets the remaining "seconds" of the video.
How can I remove the enterFrame listener? Where in the code?
It's printing the Error #1009 when jumping to the next frame of the main timeline.
Anyway, the movie is running "normally", so the question is for learning purposes.
Thanks in advance,
Cheers

removeEventListener(Event.ENTER_FRAME, updateTime2);
Is this what you wanted?

Related

Problems with an object appearing on a frame I don't want it to appear on AS3

I am a total noob at AS3, roughly 1 year experience so please be lenient with me :)
I currently am making an endless runner game and I'm making the obstacles spawn using this method
var therespawn:RespawnObject;
var thecone:trafficcone;
var started:Boolean = false;
var dx:Number = 10;
var dy:Number = 10;
stage.addEventListener(Event.ENTER_FRAME, startGame);
addEventListener(Event.ENTER_FRAME, collision);
addEventListener(Event.ENTER_FRAME, coneCollision);
function startGame(evt:Event):void {
if (started == false) {
spawnHazard();
}
}
function spawnHazard() {
started = true;
therespawn = new RespawnObject();
addChild(therespawn);
thecone = new trafficcone();
addChild(thecone);
therespawn.x = -50;
therespawn.y = 310;
thecone.x = 600;
thecone.y = 310;
}
function collision(evt:Event):void {
thecone.x -= 15;
if(thecone.hitTestObject(therespawn)) {
thecone.x = 600;
}
}
Now the only way to finish the game or end it is to get hit by an obstacle which ive shown down below:
function coneCollision(evt:Event):void {
if(MainChar.hitTestObject(thecone)) {
gotoAndStop("frameFive");
}
}
Everytime the highscore frame appears the cone is still spawning and despawning, why is that?
I haven't declared them as global?
Any help appreciated, thanks!
You can fix your problem by setting started to false:
function coneCollision(evt:Event):void {
if(MainChar.hitTestObject(thecone)) {
started = false;
gotoAndStop("frameFive");
}
}
The flash timeline really only has to with the way MovieClips are visually displayed as children of the stage. Removing an object from the timeline doesn't just suddenly nullify all the code associated with that object. In other words, your ENTER_FRAME method still runs in the background even if the object is no longer a child of the Stage, regardless of the frame number for the MovieClip. If you're serious about coding you might consider investigating in Classes and Object Oriented AS3. Classes are much nicer to work with than the Flash timeline.

Some errors in flash AS3 game, almost completed with lot of effort and help received

First I really want to thank you for all the help you have given me so far, since I did not know anything about AS3 (basics gotoAnd stuff only) I came to Stackoverflow searching for some code already made but I was encouraged by some members to make the code by myself, now after almost 2 weeks and thanks to a lot of great people my soccer penalty kick game is almost finished, I really love this place.
I know I have to work on some collisions and other stuff since currently the game is not the best (remember I’m just a newbie), but Unfortunately while checking the game functioning by playing it over and over again, I have found the following:
1- When you get 3 fails, then game is over and a play again button appears after some animation, you click on it and everything seems to be fine, but when you continue playing the second time you reach 3 fails, when you click the button a new cursor appears??? Please help
2- I tried millions of times to make the ball move with speed and to animate its trajectory but was unable to make it, any help on this will be highly appreciated. I have speed variables and gravity but I didn’t know how to use them
3- I'm getting a actionscript error related to a removeChild, I tried many times removing some lines but I´m unable to fix it.
4- I'm using too many timers, I don't know if this is recommendable.
Here is the .fla file https://rapidshare.com/files/1702748636/kicks.fla just in case anybody want to try the game (this is really simple since it is my 1st AS project) and want to help me with the code and help me improving the game, and here is the code if somebody does not need to get into the file (I know this place is full of really smart people), once I finish it I know I will be able to do a lot of stuff with AS3.
var score:Number;
var angle:Number;
var speed:Number;
var cursor:MovieClip;
var failed:Number;
var ballRotation:Boolean = false;
function initializeGame( ):void
{
ball.x = 296.35;
ball.y = 353.35;
score=0;
failed=0;
cursor = new Cursor();
addChild(cursor);
cursor.enabled = true;
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
}
function dragCursor(event:MouseEvent):void
{
cursor.x = this.mouseX;
cursor.y = this.mouseY;
}
initializeGame();
var mouse = this.Mouse;
function kick(evt:Event)
{
removeChild(cursor);
pateador_mc.play();
var timer:Timer = new Timer(500,1);
timer.addEventListener(TimerEvent.TIMER, delayedAction);
timer.start();
function delayedAction(e:TimerEvent)
{
moveBall();
}
}
speed=-100000;
var ease:int = 100;
var gravity:Number = 0.5;
function moveBall()
{
var targetX:Number = mouseX;
var targetY:Number = mouseY;
var angle = Math.atan2(targetY,targetX);
ball.x = mouseX + Math.cos(angle);
ball.y = mouseY + Math.sin(angle) ;
ballRotation = true;
stage.removeEventListener(MouseEvent.CLICK, kick);
if (ballRotation==true)
{
keeper.gotoAndStop(1 + Math.floor(Math.random() * keeper.totalFrames));
ball.play();
}
if (ball.hitTestObject ( keeper)){
ball.y=keeper.x-ball.height- ball.width;
trace ("Tomela");
}
if (ball.hitTestObject(goalie) && ball.y>69 /*&& ball.y<178 && ball.X>139 && ball.x<466*/)
{
gol_mc.play();
score ++;
showScore();
var timer3:Timer = new Timer(3000,1);
timer3.addEventListener(TimerEvent.TIMER, delayedAction3);
timer3.start();
function delayedAction3(e:TimerEvent)
{
ball.x = 296.35;
ball.y = 353.35;
stage.addEventListener(MouseEvent.CLICK, kick);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
addChild(cursor);
keeper.gotoAndStop(1);
}
}
else
{
fails_mc.play();
failed++;
var timer2:Timer = new Timer(3000,1);
timer2.addEventListener(TimerEvent.TIMER, delayedAction2);
timer2.start();
function delayedAction2(e:TimerEvent)
{
ball.x = 296.35;
ball.y = 353.35;
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
addChild(cursor);
keeper.gotoAndStop(1);
}
trace(failed);
if (failed==3) {
gameFinished();
trace("YOU LOST");
}
}
function showScore():void{
goles_txt.text ="" +score;
}
trace (score);
function gameFinished(){
gameOver.play ();
stage.removeEventListener(MouseEvent.CLICK, kick);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
timer2.stop();
Mouse.show();
this.mouseX=cursor.x ;
this.mouseY=cursor.y;
again_btn.addEventListener(MouseEvent.MOUSE_DOWN, playAgain);
}
function playAgain():void{
gameOver.gotoAndPlay(31);
fails_mc.gotoAndStop(1);
keeper.play();
var timer4:Timer = new Timer(1000,1);
timer4.addEventListener(TimerEvent.TIMER, delayedAction3);
timer4.start();
function delayedAction3(e:TimerEvent)
{
initializeGame();
}
}
}
I’ll really appreciate it guys , I promise I won’t be bothering again for a long time
1/3.
Problem 1 & 3 are the same problem. Looks like your trying to remove the cursor from the stage (removeChild) every click (so it will error after the first click because it's no longer a child of anything). Your adding it back on your delayedAction2 which doesn't run unless your hit test is true and only after 3 seconds. On initialize game you create a whole new cursor and add that to the stage which is why you get a duplicate after the first game.
Rather than removeChild the cursor, it might better to just set it's visibility to false/true and only create it once.
You'll need to use an EnterFrame handler, or timer, or tween for this. I can post an example later.
I can't figure out why you're using timers at all or need to delay your functions, except maybe to allow time for the kick animation?
You're code is very disorganized, naming functions things like 'delayedAction' is bad as it doesn't really tell you anything about the purposed of the function. You also have way too much functions inside of other functions. Here is a quick refactoring of your code I've done to hopefully teach a few things. I've also added the tween for the ball animation.
import flash.events.Event;
import fl.transitions.Tween;
import fl.transitions.TweenEvent;
var score:Number;
var cursor:MovieClip;
var failed:Number;
var ballRotation:Boolean = false;
var ballTweenX:Tween;
var ballTweenY:Tween;
var targetCursor = new Cursor(); //only want one of these and you want it to exist the whole time so keep out here.
addChild(targetCursor);
initializeGame();
function initializeGame( ):void
{
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
ball.x = 296.35;
ball.y = 353.35;
score=0;
failed=0;
targetCursor.visible = true;
Mouse.hide();
}
function dragCursor(event:MouseEvent):void
{
targetCursor.x = this.mouseX;
targetCursor.y = this.mouseY;
}
function kick(evt:Event)
{
//removeChild(targetCursor);
targetCursor.visible = false;
pateador_mc.play();
stage.removeEventListener(MouseEvent.CLICK, kick); //move this here, because you don't the option kick again while already kicking
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragCursor); //added this, you probably don't want the target moving after the click...
setTimeout(moveBall, 500);//cleaner and more efficient than using a timer for a one time delayed call.
}
function moveBall()
{
var targetX:Number = mouseX;
var targetY:Number = mouseY;
var angle = Math.atan2(targetY,targetX);
targetX = mouseX + Math.cos(angle);
targetY = mouseY + Math.sin(angle) ;
ballRotation = true;
ballTweenX = new Tween(ball, "x", null, ball.x, targetX, .3, true);
ballTweenY = new Tween(ball, "y", null, ball.y, targetY, .3, true);
ballTweenY.addEventListener(TweenEvent.MOTION_FINISH, ballTweenDone,false,0,true);
if (ballRotation==true)
{
keeper.gotoAndStop(1 + Math.floor(Math.random() * keeper.totalFrames));
ball.play();
}
}
function stopBallTween():void {
ballTweenX.stop();
ballTweenY.stop();
}
function ballTweenDone(e:TweenEvent):void {
if (ball.hitTestObject ( keeper)){
ball.y=keeper.x-ball.height- ball.width;
trace ("Tomela");
}
if (ball.hitTestObject(goalie) && ball.y>69 /*&& ball.y<178 && ball.X>139 && ball.x<466*/)
{
gol_mc.play();
score ++;
showScore();
}else
{
fails_mc.play();
failed++;
trace(failed);
if (failed==3) {
gameFinished();
trace("YOU LOST");
return; //added this because you don't want the rest of this function running if it's a game over
}
}
setTimeout(resetShot, 3000); //you had the code I put in resetShot repeated twice
trace(score);
}
function resetShot():void {
ball.x = 296.35;
ball.y = 353.35;
targetCursor.visible = true;
keeper.gotoAndStop(1);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
}
function showScore():void{
goles_txt.text ="" +score;
}
function gameFinished(){
gameOver.play();
stage.removeEventListener(MouseEvent.CLICK, kick);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
Mouse.show();
//this.mouseX=cursor.x ;
//this.mouseY=cursor.y; //These are read only properties, your can't set the mouse position...
again_btn.addEventListener(MouseEvent.MOUSE_DOWN, playAgain);
}
function playAgain(e:Event = null):void{
gameOver.gotoAndPlay(31);
fails_mc.gotoAndStop(1);
keeper.play();
setTimeout(initializeGame, 1000);
}

Flex 4 timers keep Firing

I'm trying to create a simple flex4 project which involves some timers that trigger other functions.
I don't have much experience with Action Script and even less with timer events.
Here is a bit of my code it seems to be working for the most part but you lines were I'm adding up the total score (score = score +1;) seems to just keep adding and adding when I test the application. I think its because the timers keep firing the function but I'm not sure.
private var score:int = 0;
private function submit():void {
this.currentState = 'loading';
var timer:Timer = new Timer(2200);
timer.addEventListener(TimerEvent.TIMER, removeLoading);
timer.start();
}
private function removeLoading(event:TimerEvent):void{
removeloading.play();
var timer1:Timer = new Timer(1000);
timer1.addEventListener(TimerEvent.TIMER, viewResults);
timer1.start();
this.currentState = 'results';
}
private function viewResults(event:TimerEvent):void{
if (q1_t.selected == true){
answer1m.text = 'You Answer the Question Correctly.';
score = score +1;
} else {
answer1m.text ='The Correct answer was: '+ q1_t.label;
}
if (q2_f.selected == true){
answer2m.text = 'You Answer the Question Correctly.';
score = score +1;
} else {
answer2m.text ='The Correct answer was: '+ q2_f.label;
}
finalscore.text = score.toString();
}
So I did a bit more research and turns out I hadn't included the second timer parameter.
The second parameter is the number of times that the TimerEvent.TIMER event will be dispatched before stopping. If you set the second parameter to 0 (zero) or omitted it completely, the timer would run forever (or until you called the stop() method on the timer instance.
Since I only want to run the event once I need to add 1.
From this:
var timer:Timer = new Timer(2200);
To this:
var timer:Timer = new Timer(2200,1);

This codes in Actionscript-2, Can anyone help me translate it into AS-3 please ?.......a newby pulling her hair out !

this.createEmptyMovieClip('mask_mc',0);
bg_mc.setMask(mask_mc);
var contor:Number=0;
// function drawCircle draws a circle on mask_mc MovieClip of radius r and having center to mouse coordinates
function drawCircle(mask_mc:MovieClip):Void{
var r:Number = 20;
var xcenter:Number = _xmouse;
var ycenter:Number = _ymouse;
var A:Number = Math.tan(22.5 * Math.PI/180);
var endx:Number;
var endy:Number;
var cx:Number;
var cy:Number;
mask_mc.beginFill(0x000000, 100);
mask_mc.moveTo(xcenter+r, ycenter);
for (var angle:Number = Math.PI/4; angle<=2*Math.PI; angle += Math.PI/4) {
xend = r*Math.cos(angle);
yend = r*Math.sin(angle);
xbegin =xend + r* A *Math.cos((angle-Math.PI/2));
ybegin =yend + r* A *Math.sin((angle-Math.PI/2));
mask_mc.curveTo(xbegin+xcenter, ybegin+ycenter, xend+xcenter, yend+ycenter);
}
mask_mc.endFill();
}
// contor variable is used to hold if the mouse is pressed (contor is 1) or not (contor is 0)
this.onMouseDown=function(){
drawCircle(mask_mc);
contor=1;
}
// if the mouse is hold and moved then we draw a circle on the mask_mc
this.onMouseMove=this.onEnterFrame=function(){
if (contor==1){
drawCircle(mask_mc);
}
}
this.onMouseUp=function(){
contor=0;
}
var mask_mc:MovieClip = new MovieClip();
bg_mc.setMask(mask_mc);
var contor:Number=0;
// function drawCircle draws a circle on mask_mc MovieClip of radius r and having center to mouse coordinates
function drawCircle(mask_mc:MovieClip):void{
var r:Number = 20;
var xcenter:Number = mouseX;
var ycenter:Number = mouseY;
var A:Number = Math.tan(22.5 * Math.PI/180);
var endx:Number;
var endy:Number;
var cx:Number;
var cy:Number;
mask_mc.graphics.beginFill(0x000000, 100);
mask_mc.graphics.moveTo(xcenter+r, ycenter);
for (var angle:Number = Math.PI/4; angle<=2*Math.PI; angle += Math.PI/4) {
xend = r*Math.cos(angle);
yend = r*Math.sin(angle);
xbegin =xend + r* A *Math.cos((angle-Math.PI/2));
ybegin =yend + r* A *Math.sin((angle-Math.PI/2));
mask_mc.graphics.curveTo(xbegin+xcenter, ybegin+ycenter, xend+xcenter, yend+ycenter);
}
mask_mc.graphics.endFill();
}
// contor variable is used to hold if the mouse is pressed (contor is 1) or not (contor is 0)
addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
addEventListener(MouseEvent.MOUSE_MOVE, mouseMoved);
addEventListener(MouseEvent.MOUSE_UP, mouseUp);
function mouseDown(e:MouseEvent):void{
drawCircle(mask_mc);
contor=1;
}
function mouseMoved(e:MouseEvent):void{
if (contor==1){
drawCircle(mask_mc);
}
}
function mouseUp(e:MouseEvent):void{
contor=0;
}
see how simple it was to translate? You should try to translate it yourself first and post your attempt.
This is just a direct translation of your snippet. You will have to remove the event listeners or there will be a memory leak.
These links might be useful for you:
AS2 to AS3 Migration Cheatsheet
ActionScript Migration Cookbook
Well sometimes the best way to get started with something like is just try to compile it as AS-3 and see where it blows up. Some of the code will work and then you can type the errors into google (or if you get stuck post specific questions to SO). That will be a lot easier than just trying to "translate" it if you don't know AS very well and understand the differences.
put it in flex builder
try to compile
if you get some errors, fix them
if you don't know how to fix them, google or ask the pleps

gotoAndPlay frames based on the percentage of an AS3 preloader's progress

i followed this excellent as3 preloader tutorial, and below is the code i have so far.
var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loop);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, done);
l.load(new URLRequest("content.swf"));
function loop(e:ProgressEvent):void
{
var perc:Number = e.bytesLoaded / e.bytesTotal;
percent.text = Math.ceil(perc*100).toString();
trace("loading...");
}
function done(e:Event):void
{
removeChildAt(0);
percent = null;
addChild(l);
trace("done!");
}
this loads the main content perfectly. displaying the percent of the loading progress.
now i'd like to take it a step farther. my goal is to have 3 images in 3 different frames on a timeline and have one become visible on 25% done, the second on 50% done, and the final image on 75% done.
i'm assuming i need to add some if statements but i'm having trouble figuring out what the syntax would be to listen for the percentage for flash to know what frame to move to.
thanks for reading and any help is greatly appreciated.
Add a movie clip called movieClipWithImages with the 3 images, one on each frame, to the stage, and then use the following code.
function loop(e:ProgressEvent):void
{
var perc:Number = e.bytesLoaded / e.bytesTotal;
percent.text = Math.ceil(perc*100).toString();
trace("loading...");
movieClipWithImages.gotoAndStop(Math.floor(perc*3/100)+1);
}