我正在开发一个生成轨道的轨道生成器(用于我未来的赛车游戏)。建好后,轨迹由游戏引擎等处理。Track 是元素的集合,可以是:
- 短/长直
- 慢/中/快弯
每个元素都有一个长度属性,应该在构建轨道元素时生成。元素依赖于生成之前的元素(在慢速弯道之后有快速弯道有点奇怪)。
我第一次寻求“ifing”的解决方案:
public class ElementType
{
...
public double GenerateLength()
{
switch (m_TypeEnum)
{
case ElementTypeEnum.SlowSpeedCorner:
return Parameters.SlowCornerAvgLength+Generator.GetDeviation;
...
case ElementTypeEnum.LongStraight:
default:
return Parameters.LongStraightAvgLength + Generator.GetDeviation(Parameters.LongStraightLengthMaxDeviation);
}
}
...
public IList<ElementType> GetPossibleSuccessors()
{
switch (m_TypeEnum)
{
case ElementTypeEnum.SlowSpeedCorner:
return new List<ElementType>() { new ElementType(ElementTypeEnum.SlowSpeedCorner), new ElementType(ElementTypeEnum.ShortStraight), new ElementType(ElementTypeEnum.LongStraight) };
...
case ElementTypeEnum.LongStraight:
default:
return new List<ElementType>() { new ElementType(ElementTypeEnum.SlowSpeedCorner), new ElementType(ElementTypeEnum.MediumSpeedCorner), new ElementType(ElementTypeEnum.FastSpeedCorner) };
}
}
}
public enum ElementTypeEnum : int
{
LongStraight = 1,
SlowSpeedCorner = 2,
}
生成器基于方法:
public static TrackElement GenerateElement(TrackElement Predecessor)
{
ElementType type = SelectElementType(Predecessor);
double length = type.GenerateLength();
return new TrackElement(type, length);
}
private static ElementType SelectElementType(TrackElement Predecessor)
{
IList<ElementType> successors = Predecessor.Type.GetPossibleSuccessors();
int possibleSuccessors = successors.Count;
int selected = Generator.GetInt(possibleSuccessors);
return successors[selected];
}
但正如您可以猜到的那样,当在引擎中使用它时,这是一场戏剧 - 结果是每个属性都有太多的“ifing”。所以我将元素移动到不同的类基于:
public abstract class TrackElement
{
public TrackElement(double Length)
{
m_length = Length;
}
protected abstract static double GenerateLength();
public sealed double Length
{
get
{
return m_length;
}
}
}
但是现在我在使用提供的类构建轨道时遇到了问题:
public static TrackElement GenerateElement(TrackElement Predecessor)
{
??? type = SelectElementType(Predecessor);
double length = type.GenerateLength();
return new ???(length);
}
当然我知道我不能这样做,因为 GenerateLength 是静态的,我只想起草我的问题。我怎样才能做到这一点?