简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM