Scene2D's ClickListener with custom Actor

313 Views Asked by At

On Scene2D, f I have a custom actor, how do I make my ClickListener to be able to refer to that 'customActor's fields and methods? Since for example the enter method goes:

public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) { ... }

The thing is that that fromActor Actor reference can't see the fields that I want to modify in my CustomActor... I'm aware that I could do something along:

public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {       
    if(fromActor instanceof CustomActor) {
        CustomActor actor = (CustomActor)fromActor;
    }
}

But to me that doesn't feel right, there's gotta be a more efficient way; so if you know of one, please let me know :D

1

There are 1 best solutions below

1
On BEST ANSWER

In the class where you are instantiating this click listener, add an inner class that looks like this:

class CustomListener extends ClickListener {

    private final CustomActor yourActor;

    public CustomListener(CustomActor yourActor) {
        this.yourActor = yourActor;
    }

    @Override
    public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
        this.yourActor.accessTheFieldYouWant;
    }
}

You can of course override any methods that you need, not just enter.

Then use it like this

yourActor.addListener(new CustomListener(yourActor) {
    @Override
    public void clicked(InputEvent event, float x, float y) {
    }
});

That's how I normally set things up, but you can put the custom listener class code wherever you want, or have a separate class file for it and import it.