|
-
removing an event listener from a function
Hi everyone.
I am working on a game for my university project and I have run into a bit of trouble. I have the following code here:
function launchBall() {
this.stage.addEventListener(KeyboardEvent.KEY_DOWN ,launchBallHandler);
function launchBallHandler(e:KeyboardEvent):void {
if (e.keyCode==32) {
space=true;
if (space==true) {
ball.xVel=20-Math.random()*19+1;
ball.yVel=20-Math.random()*19+1;
}
}
}
}
Its set up so that when a ball goes off screen, it resets to a coordinate and launchBall is called.
LaunchBall then adds the event listener to see when the Space key is pressed and that starts the ball moving again. The problem I have now is I cant seem to get rid of that eventListener. I have tried removeEventListener and that doesn't seem to work. I have tried:
if (ball.xVel>0 && ball.yVel>0) {
removeEventListener(KeyboardEvent.KEY_DOWN,launchB allHandler);
just below that code and that doesn't work either. It's not spitting any errors out at me but I am completely stumped.
Anybody have any idea on what I can do? Thanks for any help you can give me.
-
Total Universe Mod
couple of issues here.
You are defining launchBallHandler inside of another function which means it only exists for the life of the parent function. It's known as a local function and is generally bad practice.
Also, in that handler, you are setting the value of space to true and then immediately checking to see if it's true. Since that will always be true, you don't need the additional if statement.
actionscript Code:
function launchBall() { this.stage.addEventListener(KeyboardEvent.KEY_DOWN ,launchBallHandler); }
function launchBallHandler(e:KeyboardEvent):void { if (e.keyCode==32) { space=true; ball.xVel=20-Math.random()*19+1; ball.yVel=20-Math.random()*19+1; } }
-
Thanks so much for that.. it seems I was just over-complicating things. I have altered my code and it now works.
Thank you
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|