Gdx.input.getY 被翻转

2024-04-05

我在 LibGDX 中遇到一个问题,当我调用 Gdx.input.getY() 时,它会选择相对于屏幕中心位于应用程序另一侧的像素。

public class Main extends ApplicationAdapter {
private SpriteBatch batch;
private Texture img;
private OrthographicCamera camera;
int xPos;
int yPos;
private Vector3 tp = new Vector3();
BitmapFont font;

@Override
public void create () {
    batch = new SpriteBatch();
    img = new Texture("crosshair.png");
    camera = new OrthographicCamera();
    camera.setToOrtho(false, 1280, 720);
    font = new BitmapFont();

}

@Override
public void render () {
    yPos = Gdx.input.getY();
    xPos = Gdx.input.getX();
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.unproject(tp.set(xPos, yPos, 0));
    batch.begin();
    font.draw(batch,xPos + " , " + yPos, Gdx.input.getX() - 25, Gdx.input.getY() - 5);
    batch.draw(img, xPos, yPos);
    batch.end();
}

@Override
public void dispose () {
    batch.dispose();
    img.dispose();
}

用触摸位置减去视口高度是行不通的,因为这会用触摸坐标减去世界坐标。 (即使对于像素完美的投影,它也会是height - 1 - y)。而是使用 unproject 方法将触摸坐标转换为世界坐标。

您的代码有两个问题:

  • 您永远不会设置批量投影矩阵。
  • 即使您正在使用unproject方法,你永远不会使用它的结果。

因此,请改用以下内容:

@Override
public void render () {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    camera.unproject(tp.set(Gdx.input.getX(), Gdx.input.getY(), 0));
    font.draw(batch,tp.x+ " , " + tp.y, tp.x - 25, tp.y - 5);
    batch.draw(img, tp.x, tp.y);
    batch.end();
}

我建议阅读以下几页,其中详细描述了这一点及其背后的推理:

  • https://github.com/libgdx/libgdx/wiki/坐标系统 https://github.com/libgdx/libgdx/wiki/Coordinate-systems
  • https://xoppa.github.io/blog/pixels/ https://xoppa.github.io/blog/pixels/
  • https://github.com/libgdx/libgdx/wiki/Viewports https://github.com/libgdx/libgdx/wiki/Viewports
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Gdx.input.getY 被翻转 的相关文章

随机推荐