java - NullPointerException with Graphics2D Translate -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
i'm not having problems fixing this. i'm creating game , constructed camera follow player when moving when use method translate graphics2d class null pointer.
this problem doesn't happen time, when run game error occurs?
all objects created gr
exception in thread "thread-3" java.lang.nullpointerexception @ game.game.render(game.java:172) @ game.game.run(game.java:126) @ java.lang.thread.run(thread.java:745)
it's pointing @ line here.
g2d.translate(cam.getx(), cam.gety());
in 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
coming 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 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 camera class 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; } }
since stacktrace doesn't go deeper, can g2d
, cam
may cause of exception. since used g2d
before (as g
) , worked, problem must cam
, null
@ point.
edit: edit can see cam
initialized in class' constructor show us. 1 of following happening:
- there constructor doesn't initialize
cam
. - there other code overwrites
cam
. - your
render
method called beforecam
set in constructor. try makecam
initialization first line of constructor check this. might idea not launch gui stuff ingame
constructor @ all.
you should code either of 3 things. set breakpoints @ relevant lines check, if , when executed.
Comments
Post a Comment