我正在 Libgdx 中制作一个简单的平台游戏...我让玩家向左移动、向右移动和跳跃。该代码在桌面上运行良好,但在 Android 设备上,当玩家向左或向右移动时,不会触发 Jump。看起来很奇怪。这是我的代码...
私有(private)无效 updatePlayerForUserInput(float deltaTime) {
// check input and apply to velocity & state
if ((Gdx.input.isKeyPressed(Keys.SPACE) || isTouched(0.87f, 1,0,1f)) && world.player.grounded)
{
world.player.velocity.y += world.player.JUMP_VELOCITY;
world.player.state =2;
world.player.grounded = false;
}
if (Gdx.input.isKeyPressed(Keys.LEFT) || Gdx.input.isKeyPressed(Keys.A) || isTouched(0, 0.1f,0,1f))
{
world.player.velocity.x -=world.player.MAX_VELOCITY;
if (world.player.grounded)
world.player.state =1;
world.player.facesRight = false;
}
if (Gdx.input.isKeyPressed(Keys.RIGHT) || Gdx.input.isKeyPressed(Keys.D) || isTouched(0.2f, 0.3f,0,1f))
{
world.player.velocity.x =world.player.MAX_VELOCITY;
if (world.player.grounded)
world.player.state =1;
world.player.facesRight = true;
}
}
private boolean isTouched(float startX, float endX , float startY, float endY)
{
// check if any finge is touch the area between startX and endX
// startX/endX are given between 0 (left edge of the screen) and 1 (right edge of the screen)
for (int i = 0; i < 2; i++)
{
float x = Gdx.input.getX() / (float) Gdx.graphics.getWidth();
float y = Gdx.input.getY() / (float) Gdx.graphics.getHeight();
if (Gdx.input.isTouched(i) && (x >= startX && x <= endX) && (y>=startY && y<= endY))
{
return true;
}
}
return false;
}
我从 mzencher 的演示平台游戏 SuperKoalio 中获取了这个想法
请提出建议
最佳答案
这段代码:
float x = Gdx.input.getX() / (float) Gdx.graphics.getWidth();
float y = Gdx.input.getY() / (float) Gdx.graphics.getHeight();
始终从第一次 Activity 触摸中获取 x/y。您需要检查“第 i”次 Activity 触摸。像这样:
for (int i = 0; i < 20; i++) {
if (Gdx.input.isTouched(i)) {
float x = Gdx.input.getX(i) / (float) Gdx.graphics.getWidth();
float y = Gdx.input.getY(i) / (float) Gdx.graphics.getHeight();
if ((x >= startX && x <= endX) && (y>=startY && y<= endY)) {
return true;
}
}
return false;
此外,您可能应该迭代所有 20 个可能的触摸点,因为硬件最多可以跟踪 20 个触摸点。 (尝试将三个手指放在“跳跃”区域,然后在“向左移动”区域添加第四个手指。)
关于java - libgdx 中的输入事件在 Android 设备上无法同时工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17147141/