大家怎么了
我正在通过 libGDX 在 Box2D 中启发式地生成 Pong 克隆。Null 指针异常源自我试图在其中实现分数逻辑的 ContactListener 的 beginContact() 方法。
Box2D 世界使用两个单独的 EdgeShapes 作为传感器,用于在与球碰撞时增加分数变量(查看附图)。Ball 与两个 EdgeShapes 之间的碰撞逻辑有效,但 Ball 与 Box2D 世界中的任何其他物体之间的碰撞会使程序崩溃。
堆栈跟踪:
Exception in thread "LWJGL Application" java.lang.NullPointerException
at com.ckq3r.Pong.screens.GameScreen$2.beginContact(GameScreen.java:491)
at com.badlogic.gdx.physics.box2d.World.beginContact(World.java:876)
at com.badlogic.gdx.physics.box2d.World.jniStep(Native Method)
at com.badlogic.gdx.physics.box2d.World.step(World.java:602)
at com.ckq3r.Pong.screens.GameScreen.render(GameScreen.java:99)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.ckq3r.Pong.PongGame.render(PongGame.java:236)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:204)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:112)
有问题的代码:
/**Box2D contact listener**/
private void createContactListener() {
world.setContactListener(new ContactListener() {
@Override
public void beginContact(Contact contact) {
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
Gdx.app.log("beginContact", "between " + fixtureA.toString() + " and " + fixtureB.toString());
if(fixtureA.getBody().getUserData().equals(1) && fixtureB.getBody().getUserData().equals(2) || fixtureA.getBody().getUserData().equals(2) && fixtureB.getBody().getUserData().equals(1)){
Gdx.app.log("HIT", "goal1 contact");
score1++;
score1String = score1 + "";
}
if(fixtureA.getBody().getUserData().equals(1) && fixtureB.getBody().getUserData().equals(3) || fixtureA.getBody().getUserData().equals(3) && fixtureB.getBody().getUserData().equals(1)){
Gdx.app.log("HIT", "goal2 contact");
score2++;
score2String = score2 + "";
}
}
@Override
public void endContact(Contact contact) {
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
Gdx.app.log("endContact", "between " + fixtureA.toString() + " and " + fixtureB.toString());
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
});
}
笔记:
- 当我注释掉 beginContact() 方法中的两个条件语句时,代码运行。取消注释时,将重现该错误。
- Ball userData 是 circleBody.setUserData(1);
- 目标1 userData 是goalBody.setUserData(2);
- 目标2的用户数据是goalBody.setUserData(3);