MAGS94
MAGS94

Reputation: 510

AddListener to a specific position of an actor in LibGdx Scene2d

I have this actor HintsWindow that contains 3 TextureRegions (background, cancel, proceed).

public class HintsWindow extends Actor {

    TextureRegion bg;
    TextureRegion cancel;
    TextureRegion proceed;

    public HintsWindow() {
        bg = new TextureRegion(Gdx.files.internal("background.png"));
        cancel = new TextureRegion(Gdx.files.internal("cancel.png"));
        proceed = new TextureRegion(Gdx.files.internal("proceed.png"));
     }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        Color color = getColor();
        batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
        batch.draw(bg, 171.031f, 484.090f);
        batch.draw(cancel, 234.837f, 542.926f);
        batch.draw(proceed, 407.900f, 542.926f);
    }
}

Drawing TextureRegions works fine, but here is my question :

Is It possible to addListener not to the whole actor but to cancel and proceed so they act like buttons ?

something like that:

addListener(new ClickListener() {
    @Override
    public void clicked(InputEvent event, float x, float y) {
        // if proceed pressed --> do something
        // else if cancel pressed --> addAction(Actions.fadeOut(1.0f));
    }
});

Upvotes: 0

Views: 339

Answers (1)

icarumbas
icarumbas

Reputation: 1815

You can make your HintsWindow contain Actors instead of TextureRegions. Change them to Images.

    public class HintsWindow extends Actor {

    Image bg;
    Image cancel;
    Image proceed;

    public HintsWindow() {
        bg = new Image(new TextureRegion(Gdx.files.internal("background.png")));
        cancel = new Image(new TextureRegion(Gdx.files.internal("cancel.png")));
        proceed = new Image(new TextureRegion(Gdx.files.internal("proceed.png")));

        // here you can add listener
        cancel.addListener(new ClickListener() {
           @Override
           public void clicked(InputEvent event, float x, float y) {
             // if proceed pressed --> do something
             // else if cancel pressed --> addAction(Actions.fadeOut(1.0f));
    }
});
     }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        Color color = getColor();
        color.set(color.r, color.g, color.b, color.a * parentAlpha);
        bg.setColor(color);
        cancel.setColor(color);
        proceed.setColor(color);
    }
}

Upvotes: 1

Related Questions