Starling AS3 touch event press and hold
Asked Answered
A

1

5

I have been search for a while now for a clear example of how to code a button that allows the user to press and hold. While this happens I would like to execute some code.

I have implemented the TouchEvent.Touch and the touchPhase.Began but it only fires once.

I cant find a clear explanation on how to implement this. Any help is appreciated.

btnPress.addEventListener(TouchEvent.TOUCH, isPressed);

private function isPressed(event:TouchEvent){
    var touch:touch = event.getTouch(btnPress, TouchPhase.BEGAN);
    if(touch)
    {
        trace("pressed");
    }
}
Adim answered 1/11, 2012 at 9:51 Comment(0)
G
10

Starling TouchEvent and TouchPhase can be a little confusing at first. The TouchPhase.BEGAN only fires once, when the user starts touching the screen. If you want to execute some code while the finger is on the button, start executing on the TouchPhase.BEGAN phase and stop executing on the TouchPhase.ENDED phase (which fires also only once, when the user stops touching the screen).

For example, in your case you could do something like:

btnPress.addEventListener(TouchEvent.TOUCH, isPressed);

private function isPressed(event:TouchEvent):void
{
    var touch:Touch = event.getTouch(btnPress);

    if(touch.phase == TouchPhase.BEGAN)//on finger down
    {
        trace("pressed just now");

        //do your stuff
        addEventListener(Event.ENTER_FRAME, onButtonHold);
    }

    if(touch.phase == TouchPhase.ENDED) //on finger up
    {
        trace("release");

        //stop doing stuff
        removeEventListener(Event.ENTER_FRAME, onButtonHold);
    }
}

private function onButtonHold(e:Event):void
{
    trace("doing stuff while button pressed!");
}

Hope this helps clarify things a little!

Gerard answered 1/11, 2012 at 16:27 Comment(1)
Thank you. TouchPhase's are a little confusing to start with.Adim

© 2022 - 2024 — McMap. All rights reserved.