Search code examples
javanullpointerexceptionlibgdxcollision-detectioncircular-dependency

2 classes need another class to exist first. How can I solve this circular class dependency?


In my GameWorld class I initialize an item Rectangle in the constructor.

item1 = new Rectangle(GameRenderer.obstacle3.getX() - GameRenderer.generator2.getValue2(), GameRenderer.generator2.getValue1(), 5, 5);

The problem I'm having is that to initialize GameRenderer.obstacle3 a GameWorld must already exist, and to create a GameWorld, GameRenderer.obstacle3 must not be null.

In other words: GameRenderer.obstacle3 needs GameWorld to exist first but GameWorld needs GameRenderer.obstacle3 to exist first.

That is why I got a NullPointerException.

I use the rectangle for collision detection, i.e.

if (Intersector.overlaps(wizard.getBoundingRectangle(), item1)) { 
                GameRenderer.DoublePointsActive = true;
                addScore(5);
}

I don't know how I can solve this issue with reorganizing at least as possible.


Solution

  • I would avoid coupling these classes like this. Maybe you should rethink about your design. Why is obstacle3 member of GameRenderer and not member of GameWorld, for example? An obstacle doesn't seen to fit as a member of a renderer.