Whenever I run my program I get this error:
Exception in thread "Thread-2" java.lang.NullPointerException
at ca.wamlab.game.entities.Player.tick(Player.java:20)
at ca.wamlab.game.level.Level.tick(Level.java:38)
at ca.wamlab.game.Game.tick(Game.java:169)
at ca.wamlab.game.Game.run(Game.java:112)
at java.lang.Thread.run(Thread.java:744)
Ignore all but the first at because all of them are because of that one.
I get that error in the following code:
package ca.wamlab.game.entities;
import ca.wamlab.game.InputHandler;
import ca.wamlab.game.gfx.Colors;
import ca.wamlab.game.gfx.Screen;
import ca.wamlab.game.level.Level;
public class Player extends Mob{
private InputHandler input;
private int color = Colors.get(-1, 111, 145, 543);
public Player(Level level, int x, int y, InputHandler input) {
super(level, "Player", x, y, 1);
}
public void tick() {
int xa = 0;
int ya = 0;
if(input.up.isPressed()){
ya--;
}
if(input.down.isPressed()){
ya++;
}
if(input.right.isPressed()){
xa++;
}
if(input.left.isPressed()){
xa--;
}
if (xa != 0 || ya != 0){
move(xa, ya);
isMoving = true;
}else{
isMoving = false;
}
}
public void render(Screen screen) {
int xTile = 0;
int yTile = 28;
int modifier = 8*scale;
int xOffset = x - modifier/2;
int yOffset = y - modifier /2-4;
screen.render(xOffset, yOffset, xTile + yTile * 32, color);
screen.render(xOffset + modifier, yOffset, (xTile + 1) + yTile * 32, color);
screen.render(xOffset, yOffset + modifier, xTile + (yTile + 1) * 32, color);
screen.render(xOffset + modifier, yOffset + modifier, (xTile + 1) + (yTile + 1) * 32, color);
}
public boolean hasCollided(int xa, int ya) {
return false;
}
}
And the input class is:
package ca.wamlab.game;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class InputHandler implements KeyListener{
public InputHandler(Game game) {
game.addKeyListener(this);
}
public class Key {
private int numTimesPressed;
private boolean pressed = false;
public int getNumTimesPressed(){
return numTimesPressed;
}
public boolean isPressed(){
return pressed;
}
public void toggle(boolean isPressed){
pressed = isPressed;
if(isPressed)numTimesPressed++;
}
}
public Key up = new Key();
public Key down = new Key();
public Key right = new Key();
public Key left = new Key();
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
toggleKey(e.getKeyCode(), false);
}
public void toggleKey(int keyCode, boolean isPressed){
if(keyCode == KeyEvent.VK_W || keyCode == KeyEvent.VK_UP){ up.toggle(isPressed);}
if(keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_DOWN){ down.toggle(isPressed);}
if(keyCode == KeyEvent.VK_D || keyCode == KeyEvent.VK_RIGHT){ right.toggle(isPressed);}
if(keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_LEFT){left.toggle(isPressed);}
}
}
I know I get this because of the fact that something in the code is set to null (I think it is the ispressed()
) but I can't figure out a way to fix it...