“main” 线程中的异常,JBox2d 中的 java.lang.NullPointerException。

huangapple 未分类评论48阅读模式
英文:

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 &quot;main&quot; java.lang.NullPointerException
	at Enemy.&lt;init&gt;(Enemy.java:41)
	at Game.&lt;init&gt;(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()&lt;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);

huangapple
  • 本文由 发表于 2020年5月2日 17:26:44
  • 转载请务必保留本文链接:https://java.coder-hub.com/61557113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定