好吧,我制作了自己的小菜单,但问题很小。当我使用'w'和's'键只有播放按钮,并选择高分按钮。但是当我使用箭头键时,它们会跳过高分数按钮,只是在播放和退出之间交替。
*我正在使用libgdx
public class levelSelection implements Screen {
private SpriteBatch spriteBatch;
private Texture playB;
private Texture exitB;
private Texture hScoreB;
private Texture backGround;
MyGdxGame game;
private int selectedButton;
BitmapFont font;
public levelSelection(MyGdxGame game) {
this.game = game;
}
public void render(float delta) {
Gdx.gl.glClearColor( 0f, 0f, 0f, 1f );
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
spriteBatch.draw(backGround, 0, 0);
spriteBatch.draw(playB, 250, 450);
spriteBatch.draw(exitB, 250, 350);
spriteBatch.draw(hScoreB, 250, 400);
spriteBatch.end();
//Start Navigation Between menu buttons
if( selectedButton == 2 && Gdx.input.isKeyPressed(Input.Keys.DOWN) || Gdx.input.isKeyPressed(Input.Keys.S)){
selectedButton = 3;
System.out.println("Quit button is selected");
}
if(selectedButton == 3 && Gdx.input.isKeyPressed(Input.Keys.UP)|| Gdx.input.isKeyPressed(Input.Keys.W)){
selectedButton = 2;
System.out.println("High Scores button is selected");
}
if(selectedButton == 2 && Gdx.input.isKeyPressed(Input.Keys.UP)|| Gdx.input.isKeyPressed(Input.Keys.W)){
selectedButton = 1;
System.out.println("Play button is selected");
}
if(selectedButton == 1 && Gdx.input.isKeyPressed(Input.Keys.DOWN)|| Gdx.input.isKeyPressed(Input.Keys.S)){
selectedButton = 2;
System.out.println("High Scores button is selected");
}
//end navigation between menu buttons
if(selectedButton == 1 && Gdx.input.isKeyPressed(Input.Keys.ENTER)){
game.setScreen(game.GameScreen);
}
if(selectedButton == 3 && Gdx.input.isKeyPressed(Input.Keys.ENTER)){
game.dispose();
}
//Draw text according to selected button
if(selectedButton == 2){
spriteBatch.begin();
font.draw(spriteBatch, "High Score Button is Selected!", 15, 15);
spriteBatch.end();
}
if(selectedButton == 3){
spriteBatch.begin();
font.draw(spriteBatch, "Quit Button is Selected!", 15, 15);
spriteBatch.end();
}
if(selectedButton == 1){
spriteBatch.begin();
font.draw(spriteBatch, "Play Button is Selected!", 15, 15);
spriteBatch.end();
}
}
}
答案 0 :(得分:2)
true || false = true
false || true = true
让我们将它与selectedButton == 3结合起来(假设是假)我们没有按下第一个keydown而是第二个keydown。然后我们确实遇到这种情况false && false || true
- > false || true = true
。这不应该发生。它没有被选中,但关键ifstatemen说true
所以它不正确。 (System.out.println(false && false || true);
)
这是正确的解决方案。你总是需要检查两个conidions并用or语句连接它们:
if((selectedButton == 2 && Gdx.input.isKeyPressed(Input.Keys.DOWN)) || (selectedButton == 2 && Gdx.input.isKeyPressed(Input.Keys.S))){
selectedButton = 3;
System.out.println("Quit button is selected");
}
这将创建以下布尔状态false || false && false ||true
- > false && true
- > false
。
只要提一个更甜蜜的解决方案,你也可以使用XOR而不是2&&用||连接。
if(selectedButton == 2 && Gdx.input.isKeyPressed(Input.Keys.DOWN) ^ Gdx.input.isKeyPressed(Input.Keys.S)){
selectedButton = 3;
System.out.println("Quit button is selected");
}
或支撑钥匙或钥匙。
如果这不完全正确,我很抱歉。我不关心java的布尔顺序。