【发布时间】:2020-05-08 11:28:00
【问题描述】:
我有 2 个类:实体和控制。
实体:
public class Entity
{
public float Rotate {get; private set;}
readonly Control m_Control
public Entity(float rot)
{
Rotate = rot;
m_control = new Control();
}
public void Update(float time)
{
switch (m_control.Rotating())
{
case Control.Rotator.Right:
Rotate += time * 1.5f;
break;
case Control.Rotator.Left:
Rotate -= time * 1.5f;
break;
case Control.Rotator.Still:
break;
default:
break;
}
}
}
控制:
public class Control
{
private Random rnd = new Random();
private int _randomTurn;
public enum Rotator
{
Still,
Right,
Left
}
public Control()
{
TimerSetup(); // Initialize timer for Entity
}
public Rotator Rotating()
{
switch(_randomTurn)
{
case 1:
return Rotator.Right;
case 2:
return Rotator.Left;
default:
return Rotator.Still;
}
}
private void TimerSetup()
{
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(GameTickTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 2);
dispatcherTimer.Start();
}
private void GameTickTimer_Tick(object sender, EventArgs e)
{
RandomTurn();
}
private void RandomTurn()
{
_randomTurn = rnd.Next(1, 4);
}
}
基本上,我想将“Control”类作为基类并创建两个子类:PlayerControl 和 AIControl。目前 Player 控制输入和 AI 控制输入都在一个 Control 类中处理。
我的困境是,在 Entity 类中,我如何确定 Entity 将使用哪个 Control 类?
Entity 类当前分配 Control 类如下:
readonly Control m_Control
public Entity(float rot)
{
Rotate = rot;
m_control = new Control();
}
我在另一个类中实例化多个实体类,如下所示:
public class Environment
{
readonly Entity m_entity;
readonly Entity m_entity2;
public Environment()
{
m_entity = new Entity(90.0f);
m_entity2 = new Entity(180.0f);
}
我有没有办法确定实体在实例化时将使用哪个 Control 子类?
【问题讨论】:
标签: c# oop object inheritance polymorphism