【问题标题】:libgdx some keypresses faster than others?libgdx 某些按键比其他按键更快?
【发布时间】:2016-08-29 12:31:43
【问题描述】:

我最近开始使用 libgdx 进行编码,并构建了一个小小的“在世界中四处走动”游戏。问题是向上和向左(W 和 A)比向右和向下更快。 W,A 和 D,S 的代码没有区别。 这是我的输入处理代码,它在“渲染”之后的每一帧都被调用:

public void processInput() {
    float delta = Gdx.graphics.getDeltaTime();
    System.out.println(1.0/delta);
    if (Gdx.input.isKeyJustPressed(Keys.A)) {
        player.posX -= 100 * delta;
        player.startAnimation(0); // Animation 0 = LEFT
        elapsedTime = 0;
    } else if (Gdx.input.isKeyJustPressed(Keys.D)) {
        player.posX += 100 * delta;
        player.startAnimation(1); // Animation 1 = RIGHT
        elapsedTime = 0;
    }
    if (Gdx.input.isKeyJustPressed(Keys.W)) {
        player.posY -= 100 * delta;
        player.startAnimation(2); // Animation 2 = BACK
        elapsedTime = 0;
    } else if (Gdx.input.isKeyJustPressed(Keys.S)) {
        player.posY += 100 * delta;
        player.startAnimation(3); // Animation 3 = FRONT
        elapsedTime = 0;
    }
    if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)){
        Gdx.app.exit();
    }

    boolean pressed = false;
    if (Gdx.input.isKeyPressed(Keys.A)) {
        player.posX -= 100 * delta;
        pressed = true;
    } else if (Gdx.input.isKeyPressed(Keys.D)) {
        player.posX += 100 * delta;
        pressed = true;
    }
    if (Gdx.input.isKeyPressed(Keys.W)) {
        player.posY -= 100 * delta;
        pressed = true;
    } else if (Gdx.input.isKeyPressed(Keys.S)) {
        player.posY += 100 * delta;
        pressed = true;
    }
    if (!pressed) {
        player.stopAnimation();
    }

    if(player.posX < 0){
        player.posX = 0;
    }
    if(player.posY < 0){
        player.posY = 0;
    }
    if(player.posX > world.sizeX()*50){
        player.posX = world.sizeX()*50;
    }
    if(player.posY > world.sizeY()*50){
        player.posY = world.sizeY()*50;;
    }

    player.update(delta);
}

这里还有一个包含完整代码的 Dropbox 链接:https://www.dropbox.com/sh/p8umkyiyd663now/AAC4zt716rII-8sQpEbfuNuZa?dl=0

【问题讨论】:

  • 尝试在完美的方形窗口中运行游戏,看看您是否遇到相同的行为? stackoverflow.com/questions/21079122/…
  • 是的,先生。方形窗户也是如此。
  • 你相机的视口也是一个完美的正方形吗?
  • 是的,我只是将 Gdx.graphics.getWidth/getHeight 作为相机视口。
  • 我想你认为这个问题是屏幕分辨率的拉伸,这可以用一个完美的正方形来解决,但我可以看到玩家位置的 X 和 Y 值变化得更快而不仅仅是更快的运动。

标签: java input libgdx


【解决方案1】:

问题是您将玩家位置存储为整数值。 delta 计算后玩家速度非常小,将浮点值转换为整数会对速度产生巨大影响。

比较

作为整数的增量位置在 W 和 A 键的情况下为 2,在 S 和 D 的情况下为 1。

在这两种情况下,浮动的增量位置都在 1.7 左右。

解决方案:使用浮点值来存储玩家位置。仅在某些基于网格的游戏中使用整数值才有意义。

public float posX;
public float posY;

【讨论】:

  • 天哪,谢谢你。我现在记得我不想忘记将位置从 int 更改为 float 以防止计算的精度问题。它解决了这个问题。
猜你喜欢
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多