我正在为我的libgdx游戏创建一个菜单屏幕。如果我的菜单播放按钮被触摸,我想绘制一个矩形来检测。不幸的是,通过取消投影相机,我得到了一个Exception甚至很难我初始化相机并检查多次错误。不要怀疑OrthoCamera类它只是继承自OrthographicCamera类并具有一些额外的功能。
菜单类:
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();
播放按钮类:
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);
}
如果我点击屏幕,游戏崩溃,控制台说:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at buttons.PlayButton.update(PlayButton.java:58)
at screen.MenuScreen.update(MenuScreen.java:109)