I'm not having any problems fixing this. I'm creating a game and I constructed a camera to follow a player when they are moving but when I use the method translate from the Graphics2D class I get a null pointer.
This problem doesn't happen all the time, sometimes when I run the game the error occurs?
All objects are created for Gr
Exception in thread "Thread-3" java.lang.NullPointerException
at game.Game.render(Game.java:172)
at game.Game.run(Game.java:126)
at java.lang.Thread.run(Thread.java:745)
It's pointing at this line here.
g2d.translate(cam.getX(), cam.getY());
In my render method.
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
g2d.translate(cam.getX(), cam.getY());
handler.render(g);
g2d.translate(-cam.getX(), -cam.getY());
if (gameState == STATE.GAME) {
hud.render(g);
} else if (gameState == STATE.MENU || gameState == STATE.HELP || gameState == STATE.END) {
menu.render(g);
}
g.dispose();
bs.show();
}
Any ideas?
cam
is coming from this code:
public Game() {
tex = new Texture();
handler = new Handler();
hud = new HUD();
menu = new Menu(this, handler, hud);
this.addKeyListener(new KeyInput(handler));
this.addMouseListener(menu);
new Window(WIDTH, HEIGHT, "Let's Build A Game", this);
spawner = new Spawn(handler, hud);
// loader = new BufferedImageLoader();
// background = loader.loadImage("/level.png");
//
// loadImageLevel(background);
cam = new Camera(0, 0);
if (gameState == STATE.MENU) {
handler.createMenuParticle();
} else {
handler.clearEnemies();
}
}
This is the camera class I use.
public class Camera {
private float x, y;
public Camera(float x, float y) {
this.x = x;
this.y = y;
}
public void tick(GameObject player) {
x = -player.getX() + (Game.WIDTH / 2);
y = -player.getY() + (Game.HEIGHT / 2);
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
}