Search code examples
javaandroidlibgdxsprite

How to detect touch on sprite or texture in libGDX java?


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?


Solution

  • 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.