Reputation: 8202
I have more than one actor (for a local coop game) that need to receive key events (e.g. Player 1 uses arrow keys, Player 2 uses WASD etc...). If I just add Actors to a Stage, they don't receive key events through the InputListener, and if I do this:
stage.setKeyboardFocus(p1);
stage.setKeyboardFocus(p2);
Only Player 2 receives key events, of course. How can I have two (or more) actors receive key events?
Upvotes: 2
Views: 2488
Reputation: 759
It's curious that nobody mentioned InputMultiplexer. Try it for your situation.
Upvotes: 1
Reputation: 9793
Libgdx Stage
extends InputAdapter
, which gives you access to the methods keyDown(int keyCode)
and keyUp(int keyCode)
. If you set the Stage
as your InputProcessor
by using: Gdx.setInputProcessor(stage);
you can handle key inputs in the Stage
.
Some Pseudocode:
public boolean keyDown(int keyCode) {
switch (keyCode) {
case Input.Keys.A:
player2.moveLeft();
case Input.Keys.NUMPAD_4:
player1.moveLeft();
}
}
Hope it helps.
Upvotes: 1
Reputation: 1767
You can use a Group or a Table which are actors that can contain other actors, and add the actors
Gdx.setInputProcessor(stage);
group = new Group();
group.addActor(actor1);
group.addActor(actor2);
group.addListener(new InputListener(){
@Override
public boolean keyDown(InputEvent event, int keycode){
if (keycode == Keys.A){
update(actor1)
}
if (keycode == Keys.LEFT{
update(actor2)
}
return true;
});
stage.addActor(group);
stage.setKeyboardFocus(group);
Upvotes: 3
Reputation: 8202
Figured it out. Instead of setting the keyboard focus to the individual Actors, set it to a common actor, and then just add a listener to that actor. E.G.:
public class Scene extends Stage
{
public Scene()
{
setKeyboardFocus(getRoot()); // getRoot() returns the parent actor group
addActor(new Player(1));
addActor(new Player(2));
}
}
public class Player extends Actor
{
public Player(Stage stage)
{
stage.getRoot().addListener(inputListener);
}
}
Upvotes: -1