0
\$\begingroup\$

I have a GameScreen where I'd like to have a pause button. I've tried using an Image with a listener, but since my GameScreen isn't a stage, I can't use that in the inputProcessor. So my question is how should one create a clickable button outside a stage class?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

In general you need two textures, an up and a down to be displayed. Then you need to check to see if the touch coordinates is in bounds. Something like the below should work for your needs with little modification:

public class MyButton
{
    private Texture imgUp;
    private Texture imgDown;
    private Rectangle bounds;

    public MyButton(Texture imageUp, Texture imageDown, Rectangle bounds)
    {
        this.imgUp = imageUp;
        this.imgDown = imageDown;
        this.bounds = bounds;
    }

    public Rectangle getBounds()
    {
        return bounds;
    }

    public void update(SpriteBatch batch)
    {
        if(isTouched())
        {
            batch.draw(imgDown, bounds.getX(), bounds.getY());
        }

        else
        {
            batch.draw(imgUp, bounds.getX(), bounds.getY());
        }
    }

    public boolean isTouched()
    {
        if(bounds.contains(Gdx.input.getX(), Gdx.input.getY())
        {
            return true;
        }
        return false;
    }
}

If you want you can also define your own implementation of InputProcessor and libGdx comes with a few implementations aside from Stage. You can set InoutProcessor with:

Gdx.input.setInoutProcessor(processor);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .