Flash AS3 callback function on clearInterval - actionscript-3

I am new in Flash ActionScript 3.0. I need callback function on setInterval, I did like
There is a basket called ownmouse. and it is attached with mouse.
ownmouse.addEventListener(Event.ENTER_FRAME,fun);
function fun(Eve:Event) {
ownmouse.startDrag(true);
Mouse.hide();
}
ball fall from top of the flash document with setInterval.
var myInterval = setInterval(fallBall,1);
ownmouse.addEventListener(Event.ENTER_FRAME,controlCursor);
function controlCursor(MouseMove:Event) {
var xaxis:int = mouseX;
var yaxis:int = mouseY;
var ballXaxis = ball.x;
var ballYaxis = ball.y;
if((ballXaxis+10)>=xaxis && (ballXaxis-10)<=xaxis && (ballYaxis)>=yaxis && (ballYaxis-10)<=yaxis) {
clearInterval(myInterval, function() {
myBall.gotoAndPlay(10)
});
}
if(yaxis>620) {
ownmouse.stopDrag();
ownmouse.y = 620;
Mouse.show();
} else if(yaxis<420) {
ownmouse.stopDrag();
ownmouse.y = 430;
Mouse.show();
}
}
Everything work well except following code:
clearInterval(myInterval, function() {
myBall.gotoAndPlay(10)
});
Is callback function possible in AS3 ? If not, how to solve such problem ?
I will appreciate your help very much :)

clearInterval destroys intervals.
setInterval creates it and returns a number which you can put into clearInterval to destroy it.
also setTimeout performs it only once.
you also need to specify a time, in milliseconds, after the function.
I will always recommend you use Timer class because you can control it and read it easily.

there is no callback for clearInterval. you could trigger a method yourself if your requirements for destroying it are met.
Depending on your needs, maybe a timer would be a better choice.
var myTimer:Timer = new timer(1000,8);// set amout
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
myTimer.addEventListener(TimeEvent.TIMER_COMPLETE, timerDone);
function timerListener (e:TimerEvent):void{
trace("Timer is Triggered");
}
function timerDone(e:TimerEvent):void{
trace("Timer finishing!");
}
myTimer.start();
EDIT:
Like i said b4, you can trigger your own method when the requirements are met. In your case with the updated source:
if((ballXaxis+10)>=xaxis && (ballXaxis-10)<=xaxis && (ballYaxis)>=yaxis && (ballYaxis-10)<=yaxis) {
clearInterval(myInterval);
intervalDestroyed();
}
function intervalDestroyed():void
{
trace("Intervall has been cleared");
myBall.gotoAndPlay(10);
}
If this is the only thing you are trying to do, you can just call whatever you need in the if:
if((ballXaxis+10)>=xaxis && (ballXaxis-10)<=xaxis && (ballYaxis)>=yaxis && (ballYaxis-10)<=yaxis) {
clearInterval(myInterval);
myBall.gotoAndPlay(10);
}

Related

Objects spawn randomly in Flash actionscript 3.0

I am creating a game that a sheep need to jump or crouch to avoid obstacles.
I had create 2 types of obstacles but they come in a constant speed.
Sometimes the 2 obstacles come together make it impossible to avoid. Is there any way to change this?
Can I make the 2 obstacles come in randomly in a random speed?Here is my code.`
hole_mc.visible = false;
bird_mc.visible = false;
playhotarea_btn.addEventListener(MouseEvent.CLICK, removeInstructionBox);
function removeInstructionBox(event:MouseEvent):void
{
playhotarea_btn.removeEventListener(MouseEvent.CLICK, removeInstructionBox);
instructionbox_mc.visible = false;
instructiontext_mc.visible = false;
playbtn_mc.visible = false;
playbtntext_mc.visible = false;
sheep_mc.sheepIN_mc.visible = false;
sheep_mc.gotoAndPlay("sheepwalk");
treebg_mc.gotoAndPlay("bgloop");
hole_mc.visible = true;
bird_mc.visible = true;
timer.start();
}
hole_mc.addEventListener(Event.ENTER_FRAME, holeMove);
function holeMove(event:Event):void {
if (hole_mc.x>= -200) {
hole_mc.x -=7;
}else{
hole_mc.x=1080;
trace("hole loops");
}
}
bird_mc.addEventListener(Event.ENTER_FRAME, birdMove);
function birdMove(event:Event):void {
if (bird_mc.x>= -200) {
bird_mc.x -=10;
}else{
bird_mc.x=1080;
trace("bird loops");
}
}
stage.addEventListener(Event.ENTER_FRAME, hitHole);
function hitHole(event:Event):void{
if (sheep_mc.hitTestObject(hole_mc)){
gotoAndStop("GameOver");
hole_mc.removeEventListener(Event.ENTER_FRAME, holeMove);
stage.removeEventListener(Event.ENTER_FRAME, hitHole);
bird_mc.removeEventListener(Event.ENTER_FRAME, birdMove);
stage.removeEventListener(Event.ENTER_FRAME, hitBird);
}
}
stage.addEventListener(Event.ENTER_FRAME, hitBird);
function hitBird(event:Event):void{
if (sheep_mc.hitTestObject(bird_mc)){
gotoAndStop("GameOver");
bird_mc.removeEventListener(Event.ENTER_FRAME, birdMove);
stage.removeEventListener(Event.ENTER_FRAME, hitBird);
hole_mc.removeEventListener(Event.ENTER_FRAME, holeMove);
stage.removeEventListener(Event.ENTER_FRAME, hitHole);
}
}
var currentSecond:Number = 0;
var delay:Number = 1000;
var timer:Timer = new Timer(delay);
timer.addEventListener(TimerEvent.TIMER, timerEventHandler);
function timerEventHandler(event:TimerEvent):void
{
currentSecond++;
trace(currentSecond);
score_txt.text = String(currentSecond + " s");
}
`
You can always avoid spawning things in the same place by testing for "collision" before you create (or in your case, move) the new object. You should do the testing in whatever class has a reference to all the objects on the screen. In this case, the class you posted has references to the hole and bird, which are the two objects you want to NOT have the same x value.
Try something along the lines of:
function birdMove(event:Event):void {
if (bird_mc.x>= -200) {
bird_mc.x -=10;
}else{
if(hole_mc.x > 1000){ // See notes below
bird_mc.x=1080;
trace("bird loops");
}}}
I put 1000 under the assumption that you would want a little bit of space between the two obstacles. If you're only worried about them being EXACTLY on top of each other, then you can just use if hole_mc.x = 1080. But by using > some number, you can guarantee a little bit of room between them.
You should add a similar line to the hole mover as well so that it doesn't matter which one gets called first. They both check before they respawn.

Drawing app undo and redo function action script 3

Can anyone show me how can I make undo and redo function? so this is my current action script. I cant figure how to do it and i see some example in some web site, the action script is to long to under stand. Pls show a simple way that i can make this work..
sorry for bad grammar...
var drawingLine:Shape=new Shape();
board.addChild(drawingLine);
var doDraw:Boolean=false;
var lineSize:Number=7;
var activeColor:uint = 0x000000;
function PencilTool(event:MouseEvent):void{
board.addEventListener(MouseEvent.MOUSE_DOWN, MouseDown);
board.addEventListener(MouseEvent.MOUSE_UP, MouseUp);
}
function MouseDown(e:MouseEvent):void{
doDraw=true;
drawingLine.graphics.moveTo(drawingLine.mouseX, drawingLine.mouseY);
drawingLine.graphics.lineStyle(lineSize, activeColor);
board.addEventListener(MouseEvent.MOUSE_MOVE, MouseMove);
}
function MouseMove(e:MouseEvent):void{
var curX:Number=drawingLine.mouseX;
var curY:Number=drawingLine.mouseY;
if(doDraw && checkCoords(curX,curY)){
if(active=="Line"){
clearTemp();
temporaryDrawing.graphics.lineTo(curX,curY);
}else{
drawingLine.graphics.lineTo(curX,curY);
}
e.updateAfterEvent();
}
}
function MouseUp(event:MouseEvent):void{
doDraw=false;
}
btn_Pencil.addEventListener(MouseEvent.MOUSE_UP, PencilTool);
this,o Using two graphics,would not be the way to go
The way I would approach this is by creating a lineInfo class (seeing how you are using lines only), and have the information of startpoint, endpoint, lineColour, lineWidth, and lineAlpha .
Then create an array or Vector and populate it with a new LineInfo class, and update the graphics with the line. If you need to undo, you can set the last item use value to false, and redraw the graphics from the instruction of the array. Create a undo step integer, that keeps track of how many (counting from the back) actions should be omitted.
To improve performance, you can create a maximum of 25 instructions, and create a graphics that caches the items not in the undo list.
You could save all movements after clicks in an array or vector, then if you want to undo, you redraw all movements in the array except the last one.
Could be something like this:
var drawingLine:Shape=new Shape();
board.addChild(drawingLine);
// MOVEMENTS INFORMATION
var movements:Array = new Array();
var doDraw:Boolean = false;
var cacheIndex:int = 0;
var lineSize:Number=7;
var activeColor:uint = 0x000000;
function PencilTool(event:MouseEvent):void{
board.addEventListener(MouseEvent.MOUSE_DOWN, MouseDown);
board.addEventListener(MouseEvent.MOUSE_UP, MouseUp);
}
function MouseDown(e:MouseEvent):void{
function PencilTool(event:MouseEvent):void{
board.addEventListener(MouseEvent.MOUSE_DOWN, MouseDown);
board.addEventListener(MouseEvent.MOUSE_UP, MouseUp);
}
function MouseDown(e:MouseEvent):void{
doDraw=true;
drawingLine.graphics.moveTo(drawingLine.mouseX, drawingLine.mouseY);
drawingLine.graphics.lineStyle(lineSize, activeColor);
board.addEventListener(MouseEvent.MOUSE_MOVE, MouseMove);
lastTracing = {
mainPoint: {
x:drawingLine.mouseX,
y:drawingLine.mouseY
},
lineSize: lineSize,
activeColor:activeColor,
points:new Array()
}
cacheIndex = 0;
movements.splice(movements.length - cacheIndex, cacheIndex);
movements.push(lastTracing );
}
function MouseMove(e:MouseEvent):void{
var curX:Number=drawingLine.mouseX;
var curY:Number=drawingLine.mouseY;
if(doDraw && checkCoords(curX,curY)){
if(active=="Line"){
clearTemp();
temporaryDrawing.graphics.lineTo(curX,curY);
}else{
drawingLine.graphics.lineTo(curX,curY);
lastTracing.points.push({x:curX, y:curY});
}
e.updateAfterEvent();
}
}
function MouseUp(event:MouseEvent):void{
doDraw=false;
}
function undoFunction(event:MouseEvent=null):void {
if(cacheIndex+1 <= movements.length){
cacheIndex++;
}
drawCache();
}
function redoFunction(event:MouseEvent = null):void {
if(cacheIndex-1 >= 0){
cacheIndex--;
}
drawCache();
}
function drawCache():void {
for(var i:uint=0;i<(movements.length-cacheIndex);i++){
var tracingInfo:Object = movements[i];
drawingLine.graphics.clear();
drawingLine.graphics.moveTo(tracingInfo.mainPoint.x, tracingInfo.mainPoint.y);
drawingLine.graphics.lineStyle(tracingInfo.lineSize, tracingInfo.activeColor);
for(var j:uint=0;j<tracingInfo.points.length;j++){
drawingLine.graphics.lineTo(tracingInfo.points[j].x,tracingInfo.points[j].y);
}
}
}
btn_Pencil.addEventListener(MouseEvent.MOUSE_UP, PencilTool);

timerEvent within enterFrame function?

I'm calling a timerEvent function from enterFrame, it's running the timerEvent function on everyFrame. Is there a way to control it?
I've got my bullets firing function with timerEvent of 500, so it shoots a bullet every half a second on 24fps. It's working fine for now. Now I want to change bullet speed and skin with respect to weapon.
////////////////////////////////
//this function is called first time within an EnterFrame function
///////////////////////////////
function weaponCheck():void
{
switch (weaponState)
{
case STATE_GUN :
gun();
break;
case STATE_DOUBLE_GUN :
doubleGun();
break;
}
}
function gun():void
{
trace("single gun");
laserTimer = new Timer(600);
laserTimer.addEventListener(TimerEvent.TIMER, timerListener);
laserTimer.start();
function timerListener(e:TimerEvent):void
{
var tempLaser:MovieClip = new Laser();
var tempGunBlast:MovieClip = new Gun_blast_01();
tempLaser.x = player.x +((player.width/2)+12);
tempLaser.y = player.y;
tempGunBlast.x = stage.mouseX + 104;
tempGunBlast.y = tempLaser.y;
Lasers.push(tempLaser);
addChildAt(tempLaser,1);
addChildAt(tempGunBlast, 3);
if (tempGunBlast.currentFrame >= tempGunBlast.totalFrames)
{
removeChild(tempGunBlast);
}
}
}
function doubleGun():void
{
trace("Double gun");
doubleGunTimer = new Timer(400);
doubleGunTimer.addEventListener(TimerEvent.TIMER, timerListener2);
doubleGunTimer.start();
function timerListener2(e:TimerEvent):void
{
var tempLaser:MovieClip = new doubleG();
var tempGunBlast:MovieClip = new Gun_blast_01();
tempLaser.x = player.x +((player.width/2)+12);
tempLaser.y = player.y;
tempGunBlast.x = stage.mouseX + 104;
tempGunBlast.y = tempLaser.y;
Lasers.push(tempLaser);
addChildAt(tempLaser,1);
addChildAt(tempGunBlast, 3);
if (tempGunBlast.currentFrame >= tempGunBlast.totalFrames)
{
removeChild(tempGunBlast);
}
}
}
///////////////////////////////////////////////////
//Following function is called within an enterFrame event function
/////////////////////////////////////////////////
function playGame():void
{
weaponCheck();
blah1();
blah2();
blah3();
testForEnd();
}
function testForEnd():void
{
if (level == 3)
{
laserTimer.stop();
weaponState = STATE_DOUBLE_GUN;
weaponCheck();
}
}
So when the game runs for first time, it works fine and uses the timer event of 600 to hit the bullets, but when level == 3 and weaponState changes, the 2nd firing function doubleGun(); is called but it starts to fire the bullets on a per frame count, not on a controlled timerEvent. Please Help. Thanks.
Why don't you drop timers and use enter frame listener as a manner to count time? You are already calling weaponCheck() from an enterframe listener. Make it so that the actual gun() and doublegun() calls will only generate animation, such as firin' mah lazers and blasts, and the main function will just count time.
function weaponCheck():void
{
this.reloading+=this.weaponFiringSpeed; // you alter this to make your weapon fire slower or faster
if (this.reloading<FULLY_RELOADED) return; // we are not yet ready to fire
this.reloading=0;
switch (weaponState) // and here we fire with the gun state
{
case STATE_GUN :
gun();
break;
case STATE_DOUBLE_GUN :
doubleGun();
break;
}
}
function gun():void
{
trace("single gun");
var tempLaser:MovieClip = new Laser();
var tempGunBlast:MovieClip = new Gun_blast_01();
tempLaser.x = player.x +((player.width/2)+12);
tempLaser.y = player.y;
tempGunBlast.x = stage.mouseX + 104;
tempGunBlast.y = tempLaser.y;
Lasers.push(tempLaser);
addChildAt(tempLaser,1);
addChildAt(tempGunBlast, 3);
}
And similarly double gun. FULLY_RELOADED is a constant, reloading is a variable used to track time, it should be a property of the one who's firing.
Note, this approach requires you to manage your "tempGunBlast"s elsewhere, perhaps in the very weaponCheck function, if so, modify it as follows:
function weaponCheck():void
{
if (tempGunBlast) if (tempGunBlast.currentFrame >= tempGunBlast.totalFrames)
removeChild(tempGunBlast);
this.reloading+=this.weaponFiringSpeed; // you alter this to make your weapon fire slower or faster
if (this.reloading<FULLY_RELOADED) return; // we are not yet ready to fire
... // rest of code unchanged
You will most likely not be able to copypastely implement this, but please try.

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);
}

Disabling repeating keyboard down event in as3

now I'm trying to make the keyboard events to stop repeating.
My idea was to have a true and false condition for when the key is pressed so that it wont repeat if the key is down already.
//Mouse Event Over
keyCButton.addEventListener(MouseEvent.MOUSE_OVER, function(){gotoAndStop(2)});
//Variable
var Qkey:uint = 81;
//Key Down Event
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
var soundplayed = false;
function keydown(event:KeyboardEvent){
if (event.keyCode==Qkey) {
this.soundplayed=true;
}
}
if (this.soundplayed==false){
gotoAndPlay(3);
}
//Key Up Event
stage.addEventListener(KeyboardEvent.KEY_UP, keyup);
function keyup(event:KeyboardEvent){
this.soundplayed=false;
gotoAndStop(1);
}
doing this makes the key loop over and over without a keyboard event
I think i need to add a "&& keyDown..." to "if (this.soundplayed==true)" but i dont know how to do it without getting errors
here is the keyboard player i'm trying to fix http://soulseekrecords.org/psysci/animation/piano.html
Just another (perhaps a bit more general) way to write what Kishi already suggested:
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUp);
var downKeys:Dictionary = new Dictionary();
function keyDown(e:KeyboardEvent):void {
if(!downKeys[e.keyCode]) {
downKeys[e.keyCode] = true;
processKeyDown(e);
}
}
function keyUp(e:KeyboardEvent):void {
delete downKeys[e.keyCode];
}
function processKeyDown(e:KeyboardEvent):void {
trace(e.keyCode);
}
The processKeyDown function will be called as if keydown repeating was disabled. If you need to do something when the key is up, put that code in the keyUp function, or maybe call a processKeyUp function defined like processKeyDown.
I'm not sure what you are doing on these frames..
Is that the complete code?
Anyway, you should try something like this:
// Mouse Events
this.keyCButton.addEventListener(MouseEvent.MOUSE_OVER, function():void{ gotoAndStop(2) });
// Variables
var Qkey:uint = 81;
var soundplayed = false;
// Keyboard events
this.stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
this.stage.addEventListener(KeyboardEvent.KEY_UP, keyup);
// Event listeners
function keydown(event:KeyboardEvent){
if (event.keyCode == Qkey && !this.soundplayed) {
this.soundplayed = true;
this.gotoAndPlay(3);
}
}
function keyup(event:KeyboardEvent){
this.soundplayed = false;
this.gotoAndStop(1);
}
Notice that the keydown event listener will now execute once -- I mean.. at least the if branch -- as the soundplayed variable is used as a locking mechanism.
It'll only execute again after keyup's been executed (this.soundplayed = false).