java - libgdx 中的输入事件在 Android 设备上无法同时工作

标签 java libgdx 2d-games

我正在 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 中获取了这个想法

https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/superkoalio/SuperKoalio.java

请提出建议

最佳答案

这段代码:

    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/

相关文章:

Java 套接字服务器滞后于两个客户端

java - 我应该如何处理具有相同名称但不同类的依赖项?

java - 接口(interface)真的没有构造函数吗?

java - 如何以优化的方式查找一个非常大的文件中是否存在某个单词?

java - LibGDX FitViewport 在构造时不适合自身,但在调整大小时适合

java - LibGdx:使用手势监听器

java - Java 中的 CardLayout 通过 'cards' 之一中的操作更改

javascript - 当条件为真时,cancelAnimationFrame() 不起作用 - JS Canvas

Java8流操作被缓存?

Libgdx - 如何在单个视口(viewport)内旋转屏幕?