Storing game objects with generic object information
- by Mick
In a simple game object class, you might have something like this:
public abstract class GameObject {
protected String name;
// other properties
protected double x, y;
public GameObject(String name, double x, double y) {
// etc
}
// setters, getters
}
I was thinking, since a lot of game objects (ex. generic monsters) will share the same name, movement speed, attack power, etc, it would be better to have all that information shared between all monsters of the same type.
So I decided to have an abstract class "ObjectData" to hold all this shared information. So whenever I create a generic monster, I would use the same pre-created "ObjectData" for it. Now the above class becomes more like this:
public abstract class GameObject {
protected ObjectData data;
protected double x, y;
public GameObject(ObjectData data, double x, double y) {
// etc
}
// setters, getters
public String getName() {
return data.getName();
}
}
So to tailor this specifically for a Monster (could be done in a very similar way for Npcs, etc), I would add 2 classes. Monster which extends GameObject, and MonsterData which extends ObjectData. Now I'll have something like this:
public class Monster extends GameObject {
public Monster(MonsterData data, double x, double y) {
super(data, x, y);
}
}
This is where my design question comes in. Since MonsterData would hold data specific to a generic monster (and would vary with what say NpcData holds), what would be the best way to access this extra information in a system like this? At the moment, since the data variable is of type ObjectData, I'll have to cast data to MonsterData whenever I use it inside the Monster class.
One solution I thought of is this, but this might be bad practice:
public class Monster extends GameObject {
private MonsterData data; // <- this part here
public Monster(MonsterData data, double x, double y) {
super(data, x, y);
this.data = data; // <- this part here
}
}
I've read that for one I should generically avoid overwriting the underlying classes variables.
What do you guys think of this solution? Is it bad practice? Do you have any better solutions? Is the design in general bad? How should I redesign this if it is?
Thanks in advanced for any replies, and sorry about the long question. Hopefully it all makes sense!