我正在开发一款2D太空射击游戏,玩家只能左右移动。我在屏幕的左侧和右侧渲染了一个按钮,并不断检查它是否被触摸。这样做的问题是你必须抬起按钮的手指才能按下屏幕另一侧的按钮。我希望船朝着最后触摸的部分移动(即使你实际上没有抬起你第一次触摸的按钮的手指)。
public void keyListener(float delta){
//right movement
if(Gdx.input.isKeyPressed(Keys.RIGHT) || (Gdx.input.isTouched() && game.cam.getInputInGameWorld().x >= arrowMoveX - 40) && !isPlayerHit)
x+=SPEED*Gdx.graphics.getDeltaTime();
//left movement
if(Gdx.input.isKeyPressed(Keys.LEFT) || (Gdx.input.isTouched() && game.cam.getInputInGameWorld().x < arrowMoveWhite.getWidth() + 40) && !isPlayerHit)
x-=SPEED*Gdx.graphics.getDeltaTime();
我已经尝试在其中添加另一个if语句以检查第二个动作,但这样它只能在一个方向上起作用。 你能帮我吗?
答案 0 :(得分:1)
你需要知道的是,Android按触摸屏幕的顺序索引每个单独的触摸,索引被称为&#34;指针&#34;。例如,当您只用一根手指触摸屏幕时,触摸指针为0,第二个触摸指针为1. libGDX注册的最高指针为20。
对于您的特定情况,您只想读取当前正在读取触摸的最高指针上的输入,并且读取最高触摸的int。你可以循环遍历指针,并将int设置为任何触摸事件实际上是最高指针,这是指最近的印刷机,如下所示:
int highestpointer = -1; // Setting to -1 because if the pointer is -1 at the end of the loop, then it would be clear that there was no touch
for(int pointer = 0; pointer < 20; pointer++) {
if(Gdx.input.isTouched(pointer)) { // First check if there is a touch in the first place
int x = Gdx.input.getX(pointer); // Get x position of touch in screen coordinates (far left of screen will be 0)
if(x < arrowMoveWhite.getWidth() + 40 || x >= arrowMoveX - 40) {
highestpinter = pointer;
} // Note that if the touch is in neither button, the highestpointer will remain what ever it was previously
}
} // At the end of the loop, the highest pointer int would be the most recent touch, or -1
// And to handle actual movement you need to pass the highest pointer into Gdx.input.getX()
if(!isPlayerHit) { // Minor improvement: only check this once
if(Gdx.input.isKeyPressed(Keys.RIGHT) || (highestpointer > -1 && Gdx.input.getX(highestpointer) >= arrowMoveX - 40)) {
x+=SPEED*Gdx.graphics.getDeltaTime();
} else if(Gdx.input.isKeyPressed(Keys.LEFT) || (highestpointer > -1 && Gdx.input.getX(highestpointer) < arrowMoveWhite.getWidth() + 40)) {
x-=SPEED*Gdx.graphics.getDeltaTime();
}
}
请注意,您可能需要单独的相机绘制按钮(或任何hud元素),因为您不需要担心将屏幕坐标转换为世界坐标,因为x朝着相同的方向。
让我知道它是如何工作的,如果你需要任何改变的话!