Reputation: 3697
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");
}
}
Upvotes: 5
Views: 9233
Reputation: 5693
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!
Upvotes: 10