如何表达可以在C#中加在一起的序数/基数方向?`

时间:2015-12-19 03:50:15

标签: c# enums

对于我正在进行的个人游戏项目,我想要为角色实施8点移动 - 角色可以移动北,东北,东,东南等。

花了几分钟试图找到方法来组织这个设置在数学上方便编码,我终于找到了一个成功的设置 - 将序数(NESW)方向与大于零,一或两个的素数相关联,并计算基数方向(NE NW SE SW)来自两个序数的总和!

North: 3
Northeast: 10
East: 7
Southeast: 12
South: 5
Southwest: 14
West: 9
Northwest: 11

......一个问题:我接着尝试在C#Enum中实现它,在hindsight, and with some research中我发现这是C#不支持的方式。具体做法是:

public enum MotionDirection
{
    North = 3,
    NorthEast = 10,
    East = 7,
    SouthEast = 12,
    South = 5,
    SouthWest = 14,
    West = 9,
    NorthWest = 11
}

// ...SNIP...

MotionDirection direction;

float verticalDirection = ControlManager.GetAxis(VerticalAxis);
float horizontalDirection = ControlManager.GetAxis(HorizontalAxis);

if (verticalDirection > 0.0f)
    direction = MotionDirection.North;
else if (verticalDirection < 0.0f)
    direction = MotionDirection.South;

// Red-squigglies appear here, and they're well-earned.
if (horizontalDirection > 0.0f)
    direction += MotionDirection.East;
else
    direction += MotionDirection.West;

我这样做的原因是,我错误地记住了位掩码的概念,并认为我可以将任何整数与没有[Flags]属性的Enum属性相关联,而实际上是[Flags]属性仅允许分配二次幂值(0,1,2,4,8等)

我的问题这一次很简单 - 除了拥有像Dictionary<MotionDirection, int> directions常量之类的词典(我想到的时候不寒而栗),我要么忘记了或者对一些C#语言结构一无所知,可以让我简单地将两个MotionDirection加在一起就好像它们是两个int一样?

1 个答案:

答案 0 :(得分:2)

以下是使用0到360之间的两个数字进行操作的方法(如果你没有在显卡中内置这样的功能):

 if a = b then 
   new_direction = a
 else      
   if a < b then 
     if (b-a < 180) then
       new_direction = (a + (b-a)/2) mod 360
     else
       new_direction = (b + (360 - b + a)/2) mod 360
   else
     if (a-b < 180) then
       new_direction = (b + (a-b)/2) mod 360 
     else
       new_direction = (a + (360 - a + b)/2) mod 360