bobbyrne01
bobbyrne01

Reputation: 6745

Creating a hierarchy for shape classes within a level in Java

I'm working on a Java based game where I need to model some basic shapes. The implementation I have at the moment has a lot of duplicated attributes across shapes of the same dimensions.

Example, I have an Interactive Rectangle which is involved in Box2d world and I have a Background Rectangle which is not involved in Box2d world. But both classes need a width and height defined.

Does anyone know a better way to model this data?

Current implementation ..

current implementation

Mock idea for new implementation, however Interactive and Background can only inherit from one parent.

idea for new class diagram

The reason why I have Interactive and Background classes is so I can loop through my objects like below.

for (Background bgShape : getLevel.getBGShapes()){

    bgShape.draw(
        gl2,
        new Vec3(
            bgShape.getPosition().x,
            bgShape.getPosition().y,
            bgShape.getPosition().z));
}

for (Body body = world.getBodyList(); body != null; body = body.getNext()) {

    Interactive iaShape = (Interactive) body.getUserData();

    iaShape.draw(
        gl2,
        new Vec3(
            body.getPosition().x,
            body.getPosition().y,
            0.0f));
}

Also Interactive class defines a number of attributes which are not present in Background,

public abstract class InteractiveShape extends Shape {

    private String bodyType;
    private float density;
    private float friction;
    private float restitution;
    private boolean fixedRotation;
    private Body body;
}

Upvotes: 0

Views: 358

Answers (1)

Crazyjavahacking
Crazyjavahacking

Reputation: 9697

  1. 2nd example is much better asRectangle is really a shape, but has additional data (width and height)
  2. I don't think Iteractive and Background are necessary unless they add any additional operations (which from the picture they do not).

Upvotes: 1

Related Questions