Iulian Lita
Iulian Lita

Reputation: 13

What's the BEST WAY to check (and do something) for a touch event in libgdx?

I have a newbie question. I just started learning about libgdx and I'm a bit confused. I read the documentation/wiki, I followed some tutorials like the one from gamefromscratch and others and I still have a question.

What's the best way to check and do something for a touch/tap event?

I'm using Scenes and Actors and I found at least 4 ways (till now) of interacting with an Actor, let's say:

1) myActor.addListener(new ClickListener(){...});

2) myActor.setTouchable(Touchable.enabled); and putting the code in the act() method

3) verifying Gdx.input.isTouched() in the render() method

4) overriding touchDown, touchUp methods

Any help with some details and suggestions when to use one over the other, or what's the difference between them would be very appreciated.

Thanks.

Upvotes: 1

Views: 197

Answers (1)

noone
noone

Reputation: 19776

I've always been using the first method and I think from an OOP viewpoint, it's the "best" way to do it.

The second approach will not work. Whether you set an Actor to be touchable or not, Actor.act(float) will still be called whenever you do stage.act(float). That means you would execute your code in every frame.

Gdx.input.isTouched() will only tell you that a touch event has happened anywhere on the screen. It would not be a good idea to try to find out which actor has been hit by that touch, as they are already able to determine that themselves (Actor.hit()).

I'm not sure where you'd override touchDown and touchUp. Actors don't have these methods, so I'm assuming you are talking about a standard InputProcessor. In this case you will have the same problem like with your 3rd approach.

So adding a ClickListener to the actors you want to monitor for these kind of events is probably the best way to go.

Upvotes: 2

Related Questions