简体   繁体   中英

InputListener for the Actor

I have a problem that keyDown event is never fired in the Actor when I press any key. Though, the touchDown (for mouse clicks) works.

Actor code:

public class MapActor extends Actor {
    private TiledMap map;
    private OrthogonalTiledMapRenderer renderer;
    private int directions = 0;
    private OrthographicCamera camera;

    public MapActor(String pathToMap, OrthographicCamera camera) {
        TmxMapLoader loader = new TmxMapLoader();
        map = loader.load(pathToMap);
        renderer = new OrthogonalTiledMapRenderer(map);
        this.camera = camera;

        this.setBounds(0, 0, 500, 500);
        this.addListener(new InputListener() {
            // a - 29, w - 51, d - 32, s - 47
            @Override
            public boolean keyDown(InputEvent event, int keycode) {
                System.out.println("Test");
                return true;
            }


            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log("Touch", "touch down");
                return true;
            }
        });
    }

    @Override
    public void act(float delta) {
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);
        batch.end();
        renderer.setView(camera);
        renderer.render();
        batch.begin();
    }

    public void dispose()   {
        renderer.dispose();
        map.dispose();
    }
}

Here is how I add the Actor to the Stage :

@Override
public void create () {
    stage = new Stage(new ScreenViewport());
    Gdx.input.setInputProcessor(stage);

    MapActor mapActor = new MapActor("maps/testmap.tmx", (OrthographicCamera) stage.getCamera());
    stage.addActor(mapActor);

}

Any suggestions are welcomed.

Only the actor that has keyboard focus will receive keyboard events.

To set which actor has keyboard focus, you can use the following...

    `Stage.setKeyboardFocus(Actor actor);`

From then on, keyboard events will be passed to the specified actor.

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