else if语句第二次按下START按钮时为什么没有将loopCount设置为0

huangapple go评论54阅读模式
英文:

why is my else if statement not setting loopCount to 0 when START is pressed a second time

问题

我尝试在按下 START 一次时将 loopCount 设置为 1,如果再次按下,我希望将 loopCount 设置为 0。帮助将不胜感激。
以下是代码部分:

int frameCount = 0;
int loopCount = 0;
int buttonPressed = 0;
int backwardCount = 1;
void updateGame() {
    if (BUTTON_PRESSED(BUTTON_START)) {
        loopCount = 1;
    }
    else if (BUTTON_PRESSED(BUTTON_START) && loopCount == 1) {
        loopCount = 0;
    }
}
英文:

Im trying to set loopCount = 1 when i press START once, if pressed again I want loopCount = 0. Help would be appreciated.
here is the code

int frameCount = 0;
int loopCount = 0;
int buttonPressed = 0;
int backwardCount = 1;
void updateGame() {
    if (BUTTON_PRESSED(BUTTON_START)) {
        loopCount = 1;
    }
    else if (BUTTON_PRESSED(BUTTON_START) && loopCount == 1) {
        loopCount = 0;
    }
}

答案1

得分: 3

第一个 if 会捕捉到所有 BUTTON_PRESSED(BUTTON_START)true 时的情况。由于您希望在按下按钮时切换 loopCount,可以将这两个 if 合并为一个,只需切换变量:

if (BUTTON_PRESSED(BUTTON_START)) {
    loopCount = !loopCount;
}
英文:

The first if will catch all cases when BUTTON_PRESSED(BUTTON_START) is true. Since you want to toggle loopCount when the button is pressed, combine the two ifs into one where you just toggle the variable:

if (BUTTON_PRESSED(BUTTON_START)) {
    loopCount = !loopCount;
}

答案2

得分: 0

int frameCount = 0;
int loopCount = 0;
int buttonPressed = 0;
int backwardCount = 0;
void updateGame() {
if(BUTTON_PRESSED(BUTTON_START)) {
if(loopCount == 0) {
loopCount = 1;
} else if(loopCount == 1) {
loopCount = 0;
}
}
}

英文:

Write your program as

int frameCount = 0;
int loopCount = 0;
int buttonPressed = 0;
int backwardCount = 0;
void updateGame() {
    if(BUTTON_PRESSED(BUTTON_START)) {
        if(loopCount == 0) {
            loopCount = 1;
        } else if(loopCount == 1) {
            loopCount = 0;
        }
    }
}

huangapple
  • 本文由 发表于 2023年2月6日 13:57:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定