【发布时间】:2020-01-19 15:49:49
【问题描述】:
我有 3 个不同的类:实体、控制和环境
在 Entity 类中,我有一个 Control 变量:
readonly Control m_Control
在我的 Entity 类的构造函数中,我正在实例化 Control 类。 Entity 类中有一个 Update 方法,用于检查 Control 类中枚举的状态:
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);
}
}
Environment 类是我实例化每个实体的地方。所以我会有 2 个 Entity 实例。
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);
}
public void Update(float time)
{
m_entity.Update(time);
m_entity2.Update(time);
}
}
我的问题是,当我实例化多个实体时,这些实体中的每一个都做完全相同的事情。
例如,Control 类有一个旋转功能,但每个实例化的 Entity 在完全相同的时间以完全相同的方式移动。
对我来说,最好的方法是让每个实例化的实体独立行动?
【问题讨论】:
-
我们在这里遗漏了一些代码。请提供一个完整的最小版本(您显示一个不带参数的
Entity构造函数,然后用 3 调用一个。没有Control类的代码,也没有实际尝试更改Entity的代码) -
我认为你的 Entity 类字段是 Static 所以所有两个实例都做最后的标志
-
嗨,我现在为每个类提供了更多代码。谢谢
标签: c# .net oop object instance