Usually when I create my game objects I like each object to have a reference to my main Game object. So currently I have the following (only the relevant part of the code is shown here):
public abstract class Entity {
private Game game;
public Entity(Game game) {
this.game = game;
}
}
So when I instantiate a new Entity object from my Game class I just pass [font="Courier New"]this[/font] in the constructor. I expected any changes made to the Game object to be reflected by the game variable of the Entity class, but due to Java's pass-by-value property they aren't. This however is not the main problem as I can live without having a Game reference in each entity. The problem is that I had the same thoughts when making my input handler. I'm currently using Java 2D for the rendering and I'm just drawing on a canvas (my Game class extends Canvas) so I'm just extending the KeyAdapter class with my KeyInputHandler and passing it to the addKeyListener() method in my Game class. However I'd also like to be able to pass the KeyInputHandler object to my Player object so that I can handle all movement of the player within the Player class. However, since the KeyInputHandler is just copied into the Player object it doesn't update the instance variables when the KeyEvents are fired.
I might be going about this the wrong way (this is how I usually do it with XNA in C#) or I might just be missing something in the way I've implemented it, but if anyone could help point me in the right direction I'd be really grateful.
I'll just paste some of the relevant pieces of code from my KeyInputHandler class and my Player class, so that it might be a bit clearer what I'm trying to do.
public class KeyInputHandler extends KeyAdapter {
private boolean rightDown;
private boolean leftDown;
private boolean downDown;
private boolean upDown;
public boolean isRightDown() { return rightDown; }
public boolean isLeftDown() { return leftDown; }
public boolean isUpDown() { return upDown; }
public boolean isDownDown() { return downDown; }
public void keyPressed(KeyEvent e) { ... } // here the rightDown, leftDown, etc. variables are changed.
public void keyReleased(KeyEvent e) { ... }
}
public class Player extends Actor {
public void updateInput(KeyInputHandler keyHandler) {
if(keyHandler.isLeftDown() && !keyHandler.isRightDown()) { this.setHorizontalVelocity(-1); }
if(keyHandler.isRightDown() && !keyHandler.isLeftDown()) { this.setHorizontalVelocity(1); }
...
}
}