ERROR in animate (1023: Incompatible override. AND 1021: Duplicate function definition.) - actionscript-3

I'm new to Adobe Animate and action script so I really dont know how to fix this.
I'm creating a mcq quiz which goes like this:
if user choose answer a or b or c or d. if a is correct answer, give 1 mark, choose wrong answer 0 mark
The source of the two errors is in the function speed.
Here is the code I made so far...
import flash.events.Event;
import flash.events.EventDispatcher;
stop();
question.text="the question is"
var totalscore=3;
var currentscore=0;
function mark()
{
currentscore = currentscore + 1;
}
/* Click to Go to Scene and Play
Clicking on the specified symbol instance plays the movie from the specified scene and frame.
Instructions:
1. Replace "Scene 3" with the name of the scene you would like play.
2. Replace 1 with the frame number you would like the movie to play from in the specified scene.
*/
ans1.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);
function fl_ClickToGoToScene_24(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "quiz 2");
currentscore = currentscore + 1;
}
ans2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);
function fl_ClickToGoToScene_24(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "quiz 2");
currentscore = currentscore + 0;
}
ans3.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);
function fl_ClickToGoToScene_24(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "quiz 2");
currentscore = currentscore + 0;
}
ans4.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);
function fl_ClickToGoToScene_24(event:MouseEvent):void
{
MovieClip(this.root).gotoAndPlay(1, "quiz 2");
currentscore = currentscore + 0;
}
stop();

You have 4 functions there all with the same name. That's probably the source of the error.
Also, your script is too complicated. You don't even need 4 different handlers to begin with.
// Subscribe a single handler to all 4 buttons.
ans1.addEventListener(MouseEvent.CLICK, onAnswer);
ans2.addEventListener(MouseEvent.CLICK, onAnswer);
ans3.addEventListener(MouseEvent.CLICK, onAnswer);
ans4.addEventListener(MouseEvent.CLICK, onAnswer);
function onAnswer(e:MouseEvent):void
{
// Event.target contains the reference to the source of the event.
// Figuring if that was a correct answer is easy.
if (e.target == ans1)
{
currentscore += 1;
}
// In any case...
(root as MovieClip).gotoAndPlay(1, "quiz 2");
}

Related

Undefined Property Error 1120 moving functions?

I'm very, VERY new at flash, and I've tried really hard to figure this out but it's not working. I keep getting the same error: "1120 Access of undefined property goGame" on line 96 and "1136 Incorrect number of arguments expected 1" on line 82.
I know both of these errors has something to do with the ordering of my functions, but I find that when I move the functions to be in front of the listener, more errors pop up demanding the same thing, and the only way I can fix those is moving them in front of each other etc. etc. So I'm kind of stuck. Help would be great appreciated!
package
{
import flash.display.*;
import flash.events.*;
import flash.ui.*;
import fl.motion.MotionEvent;
import flash.utils.Timer;
import flash.utils.*;
public class StartGame extends MovieClip
{
var questions: Array=new Array();
var correctAnswers: Array=new Array("blue","Russia","10","stone","true","hydrogen and oxygen","Rapunzel","magician","The Mona Lisa","string","12","mammal","lightning bolt","lacrosse","do");
//Creates am array used for the Quiz Time function
var i = 0;
//used to track player's movements on board
var lives = 3;
//the # of lives given at the beginning of the game
var collide: Boolean;
var myTimer: Timer = new Timer(1000, 60);
//used for timer in Storming the Castle Game
var count = 0;
//used to manage chibiKing movements
//stage.addEventListener(Event.ENTER_FRAME,onFrameLoop);
//loops frames card so animation plays
//function to get to the master instructions page
//function to get the the main board
function randomNumber(){
var number=Math.round(Math.random()*5)+1;
return number;
}//end randomNumber function
function StartGame()
{
instructionsButton.addEventListener(MouseEvent.CLICK, masterInstructions);
//listener on instructions button to open the instructions page
goButton.addEventListener(MouseEvent.CLICK, playGame);
//listener on the first play button to go to the game board
}//end StartGame function
function masterInstructions (event:MouseEvent) {
gotoAndPlay(2);
//takes you to the master instructions page
goButton2.addEventListener(MouseEvent.CLICK, playGame);
//listener on the first play button to go to the game board
}// end masterInstructions function
function rollDie (event:MouseEvent) {
goRollButton.removeEventListener (MouseEvent.CLICK, rollDie);
//makes player unable to click roll button after pressing once
goRollButton.visible = false;
//removes visiblity of the roll button one clicked
goButtonGame.visible = true;
//makes game button appear so player can proceed to game
var currentRoll=randomNumber();
//randomly rolls a number between 1 and 6
outputNumber.text=String(currentRoll);
//displays the number rolled
var newMoves = i + currentRoll*10;
//moves player forward, i being the number already moved
//roll multipled by ten for frame movements of tween
gameboy.gotoAndStop(newMoves);
//player stops at the new position
i = newMoves;
//i now changed to rolled number
if (i<=300) {
bossGame();
}//if player gets to end of board, automatically start boss game
}//end rollDie function
function playGame (event: MouseEvent) {
gotoAndPlay(3);
//goes to main board game
livesOutput.text=String(lives);
//displays the 3 of lives the player has in the output box
gameBoard.addEventListener(MouseEvent.CLICK, girlJumps);
//event listener for a pop up
goRollButton.addEventListener(MouseEvent.CLICK, rollDie);
//when pressed, button calls die roll function
goButtonGame.addEventListener(MouseEvent.CLICK, goGame);
//when pressed, chooses a random mini game
ball.addEventListener(MouseEvent.MOUSE_DOWN,ballStartDrag);
ball.addEventListener(MouseEvent.MOUSE_UP, ballEndDrag);
bear.addEventListener(MouseEvent.MOUSE_DOWN, bearStartDrag);
bear.addEventListener(MouseEvent.MOUSE_UP, bearEndDrag);
//functions to create drag and drops for objects on stage game board
goButtonGame.visible=false;
//does not display go button so player must roll dice before playing game
}//end playGame function
function ballStartDrag (evt:MouseEvent) {
ball.startDrag();
}//end ballStartDrag function
function bearStartDrag (evt:MouseEvent) {
bear.startDrag();
}//end bearStartDrag function
function ballEndDrag (evt:MouseEvent) {
ball.stopDrag();
}//end ballEndDrag function
function bearEndDrag (evt:MouseEvent) {
bear.stopDrag();
}//end bearEndDrag function
function girlJumps (evt:MouseEvent) {
girlJump.gotoAndPlay(2);
//has character on board to appear by playing tween
}//end girlJumps function
function bossGame (event:KeyboardEvent) {
stage.addEventListener( KeyboardEvent.KEY_DOWN, finalBoss);
//listener to player movement when keyboard is pressed
addEventListener(Event.ENTER_FRAME,movefireball);
//listener to move the fireball
stage.addEventListener(Event.ENTER_FRAME, collision);
//listener to collisions between symbols on stage
livesBoss.text=String(lives);
//displays number of lives in text box
fireball.height = 100;
fireball.width = 100;
fireball.x=40
fireball.y=40
fireball.xVelocity=8;
fireball.yVelocity=8;
//sets fireball parameters
}//end bossGame function
function movefireball (evt: Event) {
fireball.x +=fireball.xVelocity;
fireball.y +=fireball.yVelocity;
//creates speeds of fireball
checkfireballtoWall();
//calls function
var move1:Number=Math.ceil(Math.random()*stage.stageWidth) + 1;
var move2:Number=Math.ceil(Math.random()*stage.stageWidth) + 1;
//movements randomly created for king's movements
if (count%100 == 0) {
chibiKing.x= move1;
chibiKing.y= move2;
//reassigns chibiKing's movements
}
count++;
//adds to count after so many seconds
}//end movefireball function
function checkfireballtoWall(){
const TOP: Number= 50;
const BOTTOM: Number= stage.stageHeight;
const LEFT: Number= 50;
const RIGHT: Number= stage.stageWidth - 50;
const REVERSE: int = -1;
//limits to fireball's movements
if (fireball.y<TOP) {
fireball.y=TOP;
fireball.yVelocity*=REVERSE;
}
else if (fireball.y>BOTTOM) {
fireball.y=BOTTOM;
fireball.yVelocity*=REVERSE;
}
if (fireball.x<LEFT) {
fireball.x=LEFT;
fireball.xVelocity*=REVERSE;
}
else if (fireball.x>RIGHT) {
fireball.x=RIGHT;
fireball.xVelocity*=REVERSE;
}
//reassignes fireball's direction if fireball hits a certain area
}//end checkfireballtoWall function
function finalBoss (evt: KeyboardEvent) {
if( evt.keyCode == Keyboard.LEFT )
{player.x = player.x - 6;
}
else if( evt.keyCode == Keyboard.UP )
{player.y = player.y - 6;
}
else if( evt.keyCode == Keyboard.RIGHT )
{player.x = player.x + 6;
}
else if( evt.keyCode == Keyboard.DOWN )
{player.y = player.y + 6;
}//allows player to move via keyboard control
}//end finalBoss function
function collision (evt: Event) {
if (player.hitTestObject(chibiKing)) {
gotoAndPlay(14);
//if player hits the king, automatically go to win game screen
if (player.hitTestObject(fireball)) {
lives = lives - 1;
//if player hits fireball, lose a life
if (lives == 0) {
gotoAndPlay(11);}
//if lives equal to zero, go automatically to lose game screen
livesBoss.text=String(lives);
//display the lives remaining the text box
}
}//end collision function
function dragonBattle (event:KeyboardEvent) {
//inset Dragon Battle code
}//end dragonBattle function
function goGame (event:MouseEvent) {
var gameChoose=randomNumber();
//randomly chooses a game to play from the existing mini games
if (gameChoose==1 || gameChoose == 2) {
gotoAndPlay(4);
//game 1 start screen
goButton3.addEventListener (MouseEvent.CLICK, stormingTheCastle);
//listener to go to Storming the Castle Game
}//end goGame function
else if (gameChoose==3 && correctAnswers.length>0) {
gotoAndPlay(7)
//quiz time start screen
quizTimeButton.addEventListener (MouseEvent.CLICK, quizTime);
//quiz time start
}
else {gotoAndPlay(6);
//game 2 start screen
goButton5.addEventListener (MouseEvent.CLICK, dragonBattle);
//listener to start game 2
//wizardess.addEventListener (MouseEvent.CLICK, wizardessMagic);}
}
}//end goGame function
function quizTime (event:MouseEvent) {
questions [0]= "What colour is the sky?";
questions [1]= "What is the world's biggest country in land mass?";
questions [2]= "Do Re Mi Fa So La Ti...";
questions [3]= "How many tentacles does a squid have?";
questions [4]= "In Greek Mythology, looking into Medusa's eyes would turn you to...?";
questions [5]= "True or False: Winnipeg has a hockey team.";
questions [6]= "Water is made out of...?";
questions [7]= "Which princess is the star of Disney's movie 'Tangled'?";
questions [8]= "Harry Houdini was famous for being a(n)...?";
questions [9]= "Leonardo Da Vinci famously painted what?";
questions [10]= "What type of instrument is a sitar?";
questions [11]= "How many are in a dozen?";
questions [12]= "Humans are...?";
questions [13]= "Harry Potter is famous for having a scar shaped as what on his forehead?";
questions [14]= "What is the national sport of Canada?";
//creates questions to go with answers created in startGame function
questionBox.text=questions[questions.length];
//displays the question at the end of the array
answerQuizTime.addEventListener(MouseEvent.CLICK, quiz);
//button to proceed to get quiz marker
}//end quizTime function
function quiz (evt:MouseEvent){
var userAnswer=String(answerInput.text);
//saves the user's answer in userAnswer variable
if (userAnswer==correctAnswers[questions.length]) {
questions.pop();
//removes question from end of array
lives = lives + 1;
//adds life to player's total lives
gotoAndPlay(9);
//goes to minigame win screen
}
else {
questions.pop();
//removes question from end of array
lives = lives - 1;
//removes life from player's total lives
gotoAndPlay(10);
//goes to minigame lose screen
}
}//end quiz function
// handler function for the Arrow Keys to move Player across the stage
function movePlayer(evt: KeyboardEvent) {
// if key is right arrow, move Player to the right
if (evt.keyCode == Keyboard.RIGHT) {
Player.x += 20;
// if key is left arrow, move Player to the left
} else if (evt.keyCode == Keyboard.LEFT) {
Player.x -= 20;
}
}//end movePlayer function
function stormingTheCastle (event:MouseEvent) {
// add a listener for a Frame Event
stage.addEventListener(Event.ENTER_FRAME, onFrameLoop);
// add the listener for Keyboard events to the stage
stage.addEventListener(KeyboardEvent.KEY_DOWN, movePlayer);
// create a custom speed property for each knight
//start timer
knight1.velocity = 4;
knight2.velocity = 6;
knight3.velocity = 3;
knight4.velocity = 5;
collide = false;
myTimer.start();
}//end stormingTheCastle function
// each time frame 1 plays, move each knight
//continues if no collision and count less than 60
//return each night to top if it reaches the bottom
function onFrameLoop(evt: Event) {
if (collide == false && myTimer.currentCount < 60) {
if (knight1.y > 292.2)
{knight1.y = 42.45;}
if (knight2.y > 292.2)
{knight2.y = 42.45;}
if (knight3.y > 292.2)
{knight3.y = 42.45;}
if (knight4.y > 292.2)
{knight4.y = 42.45;}
//move knights down by its speed property amount
knight1.y = knight1.y + knight1.velocity;
knight2.y = knight2.y + knight2.velocity;
knight3.y = knight3.y + knight3.velocity;
knight4.y = knight4.y + knight4.velocity;
//trace timer count
trace(myTimer.currentCount);
//if Player is hit by a knight collision is true
if (knight1.hitTestObject(Player) == true) {
collide = true;
trace("test");
}
if (knight2.hitTestObject(Player) == true) {
collide = true;
}
if (knight3.hitTestObject(Player) == true) {
collide = true;
}
if (knight4.hitTestObject(Player) == true) {
collide = true;
}
else {
if (lives == 0) {
gotoAndPlay(11);}
//trace Game Over when collision is true
trace("GAME OVER");
gotoAndPlay(10);
}
} //end onFrameLoop function
}
}//end startGame function
}//end class function
}//end package
In a class file, the order of functions and var definitions is not an issue (aside from anonymous and nested functions which you should probably steer clear of anyway).
Let's start with line 82. You call bossGame(), but when you look at the function, you've defined it so it requires a parameter:
function bossGame (event:KeyboardEvent)
It's expecting you to pass a KeyboardEvent to the function. Though I'm not sure why because looking at that function it seems to have nothing to do with Keyboard input nor does it use that event in any way.
So, take out the parameter:
function bossGame()
Or, make it optional by giving it a default value:
function bossGame(event:KeyboardEvent = null)
For the second error. Your goGame function is actually nested inside another function collision() , so it has no scope except inside the collision function. If you want to be able to access it outside of that function, then you should break it out.
As an aside, you comments beside your closing function brackets are often incorrect making it difficult to read your code.

AS3 - How to get function to run after currentFrame updates?

I have 2 copies of a MovieClip (mcA) on my main timeline. Within mcA, I have 5 more MovieClips (mcB) and this code:
addEventListener(MouseEvent.CLICK, clickedPoint);
function clickedPoint(e:MouseEvent) {
e.target.play();
setStat(e.target.parent);
}
So I toggle the frame of the mcB that was clicked, and I run a function that references the corresponding mcA on the main timeline.
In setStat, I call another function that checks the currentFrame of all the mcBs in the mcA.
getPoints(stat) {
var points = 0;
for(var i = 1; i <= 5; i++)
{
if(stat["pnt"+i].currentFrame == 2) points++;
}
trace(points);
return points;
}
My problem is that the setStat function seems to run before the currentFrame of the mcB that has been clicked on updates.
How should I change my code so that the mcB that is clicked on registers as having changed its currentFrame when I call setStat?
You could call setStat() after the next frame update. A simple way to do this is to add an ENTER_FRAME event handler which removes itself when first invoked:
function clickedPoint(e:MouseEvent) {
e.target.play();
e.target.addEventListener(Event.ENTER_FRAME, function(e:Event):void {
e.target.removeEventListener(Event.ENTER_FRAME, arguments.callee);
setStat(e.target.parent);
});
}
You can encapsulate this behavior in a function that behaves like setTimeout:
function callNextFrame(target:DisplayObject, callback:Function, ...params:Array):void {
target.addEventListener(Event.ENTER_FRAME, function(e:Event):void {
target.removeEventListener(Event.ENTER_FRAME, arguments.callee);
callback.apply(null, params);
});
}
// Usage:
callNextFrame(e.target as DisplayObject, setStat, e.target);

How to restart an SWF with a click of a button?

I have created a drag and drop mini-game and, once finished, I wish for the user to be able to click a "try again" button and have the whole thing start over.
I have read in to this and see that there are a couple of options but am stuck as to which would be best for me.
I have created an FLA with all of my library items, an AS file (MainGame.as) with the main game and all of it's functions in one class and a second AS file (MyGame.as) which calls the class file to play the game.
Which would work best for me?
I have nothing on the layers and just cannot figure out how to remove the swf and load it again with the click of a button.
Am I right in thinking that I would add the button to the MyGame file in the timerDone function?
If so, how would I use that to reload the SWF from the start?
Here is my timerDone function ...
function timerDone(e:TimerEvent=null):void
{
if (countDown == 0)
{
count = 0;
finalScore = score;
}
else
{
count = (30) - (myTimer.currentCount);
finalScore = (count * 10) + (score);
}
myText.text = "GAME OVER!";
myText.x = 195;
displayText();
myText2.text = "Your score = " + (finalScore);
displayText2();
}
I am thinking that I add the button after the last line and somehow refresh the SWF, is that right?
Or am I way off?
You should do something like that: you call the function toReplay at the end of your function timerDone:
Function timerDone, after "displayText2();"
tryAgain.addEventListener(MouseEvent.CLICK, toReplay);
Outside the function timerDone
/**
* The function toReplay calls the function init which
* initializes the Timer and all your variables.
**/
function toReplay(e:MouseEvent):void {
e.target.removeEventListener(MouseEvent.CLICK, toReplay);
init();
}
function init():void {
// Timer
count = 0;
finalScore = 0;
myText.text = "";
// etc.
}
And the function init can directly be invoked to initialize all your variables at the begining of the game:
init();

AS3 Flash how to save score in game and display on different frame

I'm working on a trivia game that has 3 rounds per level. On the frame while playing the game you can see a box with the current score and when the user has completed the round they are taken to another frame where you can see the score for all three rounds. I can't seem to get the score to display correctly. Here's an image roughly illustrating how I would like the score displayed.
Here's the code I have on round1
import flash.display.MovieClip;
import flash.events.MouseEvent;
//Button
btn_six.addEventListener(MouseEvent.MOUSE_DOWN, onPressHandler);
btn_six.buttonMode = true;
btn_six.useHandCursor = true;
function onPressHandler(myEvent:MouseEvent){
trace('Press');
btn_six.gotoAndPlay(5);
}
var saveDataObject:SharedObject;
var currentScore:int;
init();
function init():void{
saveDataObject = SharedObject.getLocal("test");
currentScore = 0;
addEventListener(Event.ENTER_FRAME, saveData);
if(saveDataObject.data.savedScore == null){
trace("No saved data yet.");
saveDataObject.data.savedScore = currentScore;
} else {
trace("Save data found.");
loadData();
}
}
function saveData(e:Event):void{
saveDataObject.data.savedScore = currentScore;
trace("Data Saved!");
saveDataObject.flush();
trace(saveDataObject.size);
}
function loadData():void{
currentScore = saveDataObject.data.savedScore;
trace("Data Loaded!");
}
var questions:Array=['"I look like a dangling parsnip in this!" she cried. "I will never __________ these jeans!',
"Tell the freckled parrot to put his car in __________.",
"When purchasing a buttercream trowel, always choose one made of __________.",
"Everybody has a cracked snowflake. The question is, __________ one is yours? ",
"Standing at the dock, the loopy basket watched the cruise ship set __________ without him. ",];
var answers:Array=[ ["wear","where"], ["idle","idol"], ["steel","steal"] ,[ "which","witch"] ,[ "sail","sale"] ];
var qno=0;var rnd1; var rnd2;
tick.visible=false;cross.visible=false;incorrect0.visible=false;incorrect1.visible=false;incorrect2.visible=false;incorrect3.visible=false;
var right_answers=0;
var wrong_answers=0;
function change_question(){
if(tick.visible){right_answers++;}
if(cross.visible){wrong_answers++;}
if(qno==questions.length){gotoAndPlay(2);}else{
tick.visible=false;cross.visible=false;
rnd1=Math.ceil(Math.random()*2);
rnd2=Math.ceil(Math.random()*questions.length)-1;
q.text=questions[rnd2];
if(questions[rnd2]=="x"){change_question();}
questions[rnd2]="x";
enable_disable(1);
if(rnd1==1){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==2){opt1.text=answers[rnd2][1];opt2.text=answers[rnd2][0];}
//if(rnd1==3){opt1.text=answers[rnd2][1];opt2.text=answers[rnd2][2];opt3.text=answers[rnd2][0];}
if(wrong_answers==0){incorrect0.visible=true;}
if(wrong_answers==1){incorrect1.visible=true;}
if(wrong_answers==2){incorrect2.visible=true;}
if(wrong_answers==3){incorrect3.visible=true;}
if(wrong_answers==3){gotoAndPlay(3);}
}}
function enable_disable(a){
if(a==0){shade1.mouseEnabled=false;shade2.mouseEnabled=false;}
if(a==1){shade1.mouseEnabled=true;shade2.mouseEnabled=true;}}
change_question();
function ButtonAction1(eventObject:MouseEvent) {qno++;change_question();}
shade1.addEventListener(MouseEvent.CLICK, ButtonAction2);
shade2.addEventListener(MouseEvent.CLICK, ButtonAction3);
function ButtonAction2(eventObject:MouseEvent) {
enable_disable(0);if(rnd1==1) {tick.visible=true;tick.y=shade1.y}else{cross.visible=true;cross.y=shade1.y}
qno++;change_question();
}
function ButtonAction3(eventObject:MouseEvent) {
enable_disable(0);if(rnd1==2){tick.visible=true;tick.y=shade2.y}else{cross.visible=true;cross.y=shade2.y}
qno++;change_question();
}
stop();
On round 1 cleared the code looks like this:
ra.text=right_answers +"/5";
if(wrong_answers==3){gotoAndPlay(3);}
The code is the same on round 2 as round 1
and here's the code on round 2 cleared:
ra2.text=right_answers_r2 +"/10";
if(wrong_answers==3){gotoAndPlay(3);}
addEventListener(Event.ENTER_FRAME,myFunction);
function myFunction(event:Event) {
trace("Do Something");
showScoreText();
}
function showScoreText():void{
MovieClip(root).round1.loadData();
ra.text = MovieClip(root).round1.loadData("");
trace("Score text visible");
}
Change your loadData function to:
function loadData(){
currentScore = saveDataObject.data.savedScore;
trace("Data Loaded!");
return currentScore;
//^One does not simply expect something returned without returning anything
}
and there's no accepted parameter, so change
ra.text = MovieClip(root).round1.loadData("");
to
ra.text = MovieClip(root).round1.loadData();
try this,
just assume you have completed round 1 and your currentScore is 10 now you are going to round 2 that is on frame 2 and you have a score textfield in the stage now you have to append the text like this score_txt.appendText(String(currentScore)+"\n"); This helps to see both scores round 1 & round 2 keep doing this for all round. Thats it.
you can store the currentScore at the end of the each rounds in associative array and display it.
var scorearray:Array = [{scored:5, outof:10},{scored:10, outof:20},{scored:20, outof:30}];
function displayScore():void
{
for(var i:int=0;i<scorearray.length; i++)
{
var texts:TextField = new TextField();
texts.text = scorearray[i].scored +"/" + scorearray[i].outof;
texts.y = i * 20 + 30;
addChild(texts)
}
}
displayScore();

EventListener AS3 problems reset problems

Hey guys I am having a problem with Event Listeners in my AS3 file. I am trying to make this object that lasts for 83 frames to appear in a different location every time the parent (83 frame) movie clip resets. The problem is I have a function that places the object at a random y value which works great once. When it resets the ojbect appears on the same Y point. This is because I removeEventListener the function otherwise the object goes shooting off the screen when it loads. How do I call that event listener again without causing a loop that will shoot the object off screen?
Here is my code:
import flash.events.Event;
stop();
addEventListener(Event.ENTER_FRAME, SeaWeedPostion);
//stage.addEventListener(Event.ADDED_TO_STAGE, SeaWeedPostion);
function SeaWeedPostion(e:Event):void{
// if(newSeaWeed == 1) {
var randUint:uint = uint(Math.random() *500 + 50);
this.seaweedSet.y += randUint;
trace(randUint);
stopPos();
//}else{
//nothing
// }
}
function stopPos():void{
removeEventListener(Event.ENTER_FRAME, SeaWeedPostion);
//var newSeaWeed = 0;
}
function resetSeaWeed():void{
addEventListener(Event.ENTER_FRAME, SeaWeedPostion);
}
I have some // code in there from trying different things.
Anyone have any suggestions?
Thanks!
ENTER_FRAME event is triggered every frame, so rather than changing position on each frame maybe it's better to create a counter, count frames and if it reaches 82 change position of SeaWeed.
var counter:uint = 0;
Now add ENTER_FRAME listener
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function SeaWeedPostion(e:Event):void {
counter++;
//Are we there yet?
if(counter < 83) {
//Nope, carry on
}
else {
//Yey!
changePosition();
counter = 0;
}
}
//Reset SeaWeed position when called
function changePosition() {
var randUint:uint = uint(Math.random() *500 + 50);
this.seaweedSet.y += randUint;
trace(randUint);
}