我正在用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
设置为适当的值。如果这些条件的无为真,请将状态设置为State::Still
。我的代码有效,但感觉我做错了。肯定有更好的办法。我的问题是:
仅当所有指定条件失败时如何执行块,并且如果一个或多个条件为真,则执行特定于每个条件的块,而不使用嵌套if
和像我一样有很多||
运营商?
答案 0 :(得分:3)
我认为你可以这样做:
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解决方案可以正常工作,即使用布尔值。
答案 1 :(得分:2)
如果State :: Still不是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;
也可能是嵌套的方法,但它非常丑陋,可能没有更好的性能。
答案 2 :(得分:2)
取自评论中的点点滴滴。也许这样的事情(假设没有一个运动状态保持值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;
或者,如果你有更多类似于移动块的代码块,你可以创建一个临时状态变量,以相同的方式处理它并合并临时状态和原始状态。