我正在用c++制作一个小游戏,我想知道如何优化我的分支。看看这段代码:
if (
isUpPressed ||
isDownPressed ||
isLeftPressed ||
isRightPressed ||
isSpacePressed
) {
if (isUpPressed)
state |= State::MoveUp;
if (isDownPressed)
state |= State::MoveDown;
if (isLeftPressed)
state |= State::MoveLeft;
if (isRightPressed)
state |= State::MoveRight;
if (isSpacePressed)
state |= State::Jump);
} else
state = State::Still;
我想实现的是:如果按上、下、左、右或空格键,将state
设置为相应的值。如果none为true,则设置状态为State::Still
。我的代码可以工作,但是感觉我做错了。一定有更好的办法。我的问题是:
如何仅在所有指定条件失败时执行块,并在一个或几个为真时执行特定于每个这些条件的块,而不像我那样使用嵌套的if
和许多||
操作符?
我认为你可以这样做:
state = State::Still;
if (isUpPressed)
state |= State::MoveUp;
if (isDownPressed)
state |= State::MoveDown;
if (isLeftPressed)
state |= State::MoveLeft;
if (isRightPressed)
state |= State::MoveRight;
if (isSpacePressed)
state |= State::Jump;
这样,如果没有键被按下,state
被设置为Still
。
如果state
之前不为0,则可以使用meneldal解决方案,即使用布尔值
摘自评论中的点点滴滴。可能是这样的(假设没有一个移动状态的值为0)
State::Value state = State::Value(0);
if (isUpPressed)
state |= State::MoveUp;
if (isDownPressed)
state |= State::MoveDown;
if (isLeftPressed)
state |= State::MoveLeft;
if (isRightPressed)
state |= State::MoveRight;
if (isSpacePressed)
state |= State::Jump);
if(state == State::Value(0))
state = State::Still;
if(isOnFire)
state |= State::Fire;
或者,如果您有更多类似于移动块的代码块,您可以创建一个临时状态变量,以相同的方式处理它并合并临时状态和原始状态。
如果State::仍然不是0,您可以在每个分支中设置一个布尔值。设置布尔值是一个非常快的操作,所以它可能比第一种方法快。例如
bool still=true;
if (isUpPressed)
still=false, state |= State::MoveUp;
if (isDownPressed)
still=false, state |= State::MoveDown;
if (isLeftPressed)
still=false, state |= State::MoveLeft;
if (isRightPressed)
still=false, state |= State::MoveRight;
if (isSpacePressed)
still=false, state |= State::Jump;
if(still)
state=State::Still;
也可能有嵌套的方法,但它非常丑陋,可能没有更好的性能。