Недавно я начал работать над небольшой игрой для собственного развлечения, используя Microsoft XNA и C#. Мой вопрос касается проектирования игрового объекта и объектов, которые его наследуют. Я собираюсь определить игровой объект как что-то, что можно отобразить на экране. Поэтому для этого я решил создать базовый класс, который все остальные объекты, которые нужно будет отображать, наследуют, называемые GameObject. Код ниже класс я сделал:Проектирование игровых объектов
class GameObject
{
private Model model = null;
private float scale = 1f;
private Vector3 position = Vector3.Zero;
private Vector3 rotation = Vector3.Zero;
private Vector3 velocity = Vector3.Zero;
private bool alive = false;
protected ContentManager content;
#region Constructors
public GameObject(ContentManager content, string modelResource)
{
this.content = content;
model = content.Load<Model>(modelResource);
}
public GameObject(ContentManager content, string modelResource, bool alive)
: this(content, modelResource)
{
this.alive = alive;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale)
: this(content, modelResource, alive)
{
this.scale = scale;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position)
: this(content, modelResource, alive, scale)
{
this.position = position;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation)
: this(content, modelResource, alive, scale, position)
{
this.rotation = rotation;
}
public GameObject(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity)
: this(content, modelResource, alive, scale, position, rotation)
{
this.velocity = velocity;
}
#endregion
}
Я оставил из дополнительных методов, которые делают такие вещи, как поворот, перемещение, и нарисовать объект. Теперь, если бы я хотел создать другой объект, например корабль, я бы создал класс Ship, который наследует GameObject. Пример кода ниже:
class Ship : GameObject
{
private int num_missiles = 20; // the number of missiles this ship can have alive at any given time
private Missile[] missiles;
private float max_missile_distance = 3000f; // max distance a missile can be from the ship before it dies
#region Constructors
public Ship(ContentManager content, string modelResource)
: base(content, modelResource)
{
InitShip();
}
public Ship(ContentManager content, string modelResource , bool alive)
: base(content, modelResource, alive)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale)
: base(content, modelResource, alive, scale)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position)
: base(content, modelResource, alive, scale, position)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation)
: base(content, modelResource, alive, scale, position, rotation)
{
InitShip();
}
public Ship(ContentManager content, string modelResource, bool alive, float scale, Vector3 position, Vector3 rotation, Vector3 velocity)
: base(content, modelResource, alive, scale, position, rotation, velocity)
{
InitShip();
}
#endregion
}
Опять же, я отказался от каких-либо дополнительных методов, связанных с судном, например, стрельбы из ракеты. Считаете ли вы, что такой дизайн хорош или он должен быть каким-то образом улучшен или полностью изменен? Похоже, что конструкторы для дочерних классов грязны, но, возможно, это единственный способ сделать это. Я никогда не делал ничего подобного, и мне интересно, не уйду ли я в путь.
Спасибо всем, кто оставил ответ. Они были очень полезны. Похоже, что существует общее мнение о том, что изменить его вокруг, чтобы использовать шаблон MVC, было бы лучше всего. Я еще раз посмотрю, как это сделать. Я также удалю большинство конструкторов и будет иметь только один конструктор, потому что все аргументы после modelResource не нужны для создания объекта, и все они могут быть изменены позже через вызовы методов.
@NM: +1, здесь, здесь меньше конструкторов больше свойств! – user7116 2008-10-08 03:39:11