Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 Run code continuously while holding a Button down - Air For iOS/Android

I am developing an iOS game in Flash CS6. I have a basic movement test that I put in an Event.MOUSE_DOWN handler.

What I'm expecting/wanting is when I held my finger down on the button, that the player would keep moving until I stop touching the screen.

What happens though, is I have to keep constantly tapping to keep the player moving - rather than just hold my finger on the button and the player keeps moving.

What code should I use to accomplish what I want?

like image 917
user1666767 Avatar asked Sep 12 '12 19:09

user1666767


1 Answers

To accomplish this, you'll need to run a function continuously in between MouseEvent.MOUSE_DOWN and Event.MOUSE_UP as MouseEvent.MOUSE_DOWN will only get dispatched one time per press.

Here is a simple script to do just that:

myButton.addEventListener(MouseEvent.MOUSE_DOWN,mouseDown);

function mouseDown(e:Event):void {
    stage.addEventListener(MouseEvent.MOUSE_UP,mouseUp); //listen for mouse up on the stage, in case the finger/mouse moved off of the button accidentally when they release.
    addEventListener(Event.ENTER_FRAME,tick); //while the mouse is down, run the tick function once every frame as per the project frame rate
}

function mouseUp(e:Event):void {
    removeEventListener(Event.ENTER_FRAME,tick);  //stop running the tick function every frame now that the mouse is up
    stage.removeEventListener(MouseEvent.MOUSE_UP,mouseUp); //remove the listener for mouse up
}

function tick(e:Event):void {
    //do your movement
}

As an aside, you may want to use the TOUCH events, as it gives more flexibility with multi-touch control. Though if you're only ever going to allow one item to be pressed at any given time, it's not an issue.

TO do that, just add Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT in your document class, then replace your MouseEvent listeners with the appropriate touch event:

MouseEvent.MOUSE_DOWN becomes: TouchEvent.TOUCH_BEGIN
MouseEvent.MOUSE_UP becomes: TouchEvent.TOUCH_END

like image 181
BadFeelingAboutThis Avatar answered Sep 28 '22 02:09

BadFeelingAboutThis