I have a home button icon which is just a normal sprite with an image in it. I want to perform some actions on the touch of this button. How can I add touch listener to this button or is there any other simpler way to do this?
Asked
Active
Viewed 493 times
0
-
2Possible duplicate of [LibGdx, How to handle touch event?](https://stackoverflow.com/questions/35287866/libgdx-how-to-handle-touch-event) – nullPointer Mar 08 '19 at 15:22
-
Here https://stackoverflow.com/questions/24501268/how-do-i-detect-if-a-sprite-was-touched-in-java-libgdx or https://stackoverflow.com/questions/24834399/how-to-detect-if-a-texture-has-been-touched-libgdx-without-scene2d – CJR Mar 08 '19 at 16:10
-
What's about an ImageButton? – Morchul Mar 11 '19 at 07:48
1 Answers
0
One way of doing this, is to set a Rectangle
with the button bounds of your button.
Rectangle buttonBounds = new Rectangle(buttonX, buttonY, buttonWidth, buttonHeight);
If you then want to check if the user touched the button, in your render()
method, put:
if(Gdx.input.justTouched()){
Vector2 touch = viewport.unproject(new Vector2(Gdx.input.getX(), Gdx.input.getY()));
//Check if button if touched
if(buttonBounds.contains(touch)){
System.out.println("Button touched!");
//Do something
}
}
If you don't use a Viewport
, you can change viewport.unproject()
to cam.unproject()
, where cam
is your Camera
.

TVASO
- 481
- 3
- 15