im currently creating a Menu Screen for my libgdx Game. I want to draw a Rectangle to dectect if my Menu Play Button is touched. Unfortunately by unprojecting the camera i get a Exception even tough i initialized the camera and checked muliple times for mistakes. Dont wonder about the OrthoCamera Class it just inheriting from the OrthographicCamera class and has some additional Functions.
Menu Class:
public class MenuScreen extends Screen {
private OrthoCamera cam;
private PlayButton pb;
private ExitButton eb;
private Background bg;
@Override
public void create() {
// TODO Auto-generated method stub
cam = new OrthoCamera();
cam.resize():
pb = new PlayButton();
eb = new ExitButton();
bg = new Background();
Play Button Class:
public class PlayButton {
Texture texture;
Sprite sprite;
public PlayButton(){
texture = new Texture("button.png");
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion region = new TextureRegion(texture, 59, 52, 300,250);
sprite = new Sprite(region);
sprite.setSize(sprite.getWidth() / 2, sprite.getHeight() / 2);
sprite.setOrigin(-sprite.getWidth() / 2, -sprite.getHeight() / 2);
sprite.setPosition(MyGdxGame.WIDTH / 2 - 317, MyGdxGame.HEIGHT /2 -110);
}
public void render(SpriteBatch batch) {
// TODO Auto-generated method stub
System.out.println("es wird gerendert");
sprite.draw(batch);
}
public void update(OrthoCamera cam) {
// Source: http://stackoverflow.com/questions/24834399/how-to-detect-if-a-texture-has-been-touched-libgdx-without-scene2d
System.out.println("update");
if(Gdx.input.isTouched())
{
Vector3 tmp = new Vector3(Gdx.input.getX(),Gdx.input.getY(),0);
cam.unproject(tmp);
Rectangle textureBounds=new Rectangle((MyGdxGame.WIDTH / 2-317),
(MyGdxGame.HEIGHT /2 -110), 300, 250 );
if(textureBounds.contains(tmp.x,tmp.y))
{
ScreenManager.setScreen(new GameScreen());
}
}
}
}
@Override
public void render(SpriteBatch batch) {
batch.begin();
bg.render(batch);
pb.render(batch);
eb.render(batch);
batch.end();
}
public void update(OrthoCamera cam) {
// TODO Auto-generated method stub
//cam.update();
pb.update(cam);
}
If i click on the screen the Game crashes and the console says:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at buttons.PlayButton.update(PlayButton.java:58)
at screen.MenuScreen.update(MenuScreen.java:109)