0

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);
  • Then, clearly `body` is `null`. So `this.body = world.createBody(bodyDef);` the `createBody` method returned `null`. We can not help you further since you did not post the methods code. – Zabuzard May 02 '20 at 09:29
  • Please do not ommit curly braces, even if you just have a one-line statement. It is a really quick pitfall for bugs. Your `do-while` looks super scary. – Zabuzard May 02 '20 at 09:31

0 Answers0