英文:
Exception in thread "main" java.lang.NullPointerException in JBox2d
问题
我正在尝试使用Box2D制作一个简单的Java游戏,但它有50%的几率崩溃。
异常线程"main" java.lang.NullPointerException
位于 Enemy.<init>(Enemy.java:41)
位于 Game.<init>(Game.java:27)
位于 Game.main(Game.java:110)
进程以退出代码-1结束
以下是函数:
public Enemy(int size, World world, Player p) {
super(ID.Enemy,size);
Random rand = new Random();
Vec2 pos = new Vec2();
do pos.set(rand.nextInt(Game.width),rand.nextInt(Game.height));
while(pos.sub(p.body.getPosition()).length()<100.0);
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position.set(pos.x/10f,pos.y/10f);
this.body = world.createBody(bodyDef);
CircleShape shape = new CircleShape();
shape.setRadius(size/10f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = 1;
fixtureDef.restitution = 0;
fixtureDef.shape = shape;
body.createFixture(fixtureDef);
body.setUserData(this);
this.target = p.body.getPosition();
this.dir = new Vec2();
}
编译器说问题出在这一行:
body.createFixture(fixtureDef);
英文:
I'm trying to make a simple game in java with Box2D but it crashes 50% of the time.
Exception in thread "main" java.lang.NullPointerException
at Enemy.<init>(Enemy.java:41)
at Game.<init>(Game.java:27)
at Game.main(Game.java:110)
Process finished with exit code -1
Here's the function:
public Enemy(int size, World world, Player p) {
super(ID.Enemy,size);
Random rand = new Random();
Vec2 pos = new Vec2();
do pos.set(rand.nextInt(Game.width),rand.nextInt(Game.height));
while(pos.sub(p.body.getPosition()).length()<100.0);
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position.set(pos.x/10f,pos.y/10f);
this.body = world.createBody(bodyDef);
CircleShape shape = new CircleShape();
shape.setRadius(size/10f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = 1;
fixtureDef.restitution = 0;
fixtureDef.shape = shape;
body.createFixture(fixtureDef);
body.setUserData(this);
this.target = p.body.getPosition();
this.dir = new Vec2();
}
The compiler says the problem is on the line
body.createFixture(fixtureDef);
专注分享java语言的经验与见解,让所有开发者获益!
评论