[英]libgdx coordinate system differences between rendering and touch input
我有一個呈現PNG圖像的屏幕(BaseScreen實現了Screen界面)。 單擊屏幕時,它會將角色移動到觸摸位置(用於測試目的)。
public class DrawingSpriteScreen extends BaseScreen {
private Texture _sourceTexture = null;
float x = 0, y = 0;
@Override
public void create() {
_sourceTexture = new Texture(Gdx.files.internal("data/character.png"));
}
.
.
}
在渲染屏幕期間,如果用戶觸摸屏幕,我抓住觸摸的坐標,然后使用這些來渲染角色圖像。
@Override
public void render(float delta) {
if (Gdx.input.justTouched()) {
x = Gdx.input.getX();
y = Gdx.input.getY();
}
super.getGame().batch.draw(_sourceTexture, x, y);
}
問題是從左下角開始繪制圖像的坐標(如LibGDX Wiki中所述),觸摸輸入的坐標從左上角開始。 所以我遇到的問題是我點擊右下角,它將圖像移動到右上角。 我的坐標可能是X 675 Y 13,觸摸時它將靠近屏幕頂部。 但是角色顯示在底部,因為坐標從左下角開始。
為什么是這樣的? 為什么坐標系會反轉? 我使用錯誤的對象來確定這個嗎?
要檢測碰撞,我使用camera.unproject(vector3)
。 我將vector3
設置為:
x = Gdx.input.getX();
y = Gdx.input.getY();
z=0;
現在我在camera.unproject(vector3)
傳遞此向量。 使用此向量的x
和y
繪制角色。
你說得對。 Libgdx通常以“原生”格式提供坐標系統(在本例中為原生觸摸屏坐標和默認的OpenGL坐標)。 這不會創建任何一致性,但它確實意味着庫不必介入您和其他所有內容。 大多數OpenGL游戲都使用相機將相對任意的“世界”坐標映射到屏幕上,因此世界/游戲坐標通常與屏幕坐標非常不同(因此一致性是不可能的)。 請參閱更改LibGDX中的坐標系(Java)
有兩種方法可以解決這個問題。 一個是轉換你的觸摸坐標。 另一種是使用不同的相機(不同的投影)。
要修復觸摸坐標 ,只需從屏幕高度中減去y即可。 這有點像黑客。 更一般地說,您希望從屏幕“ Camera.unproject()
”到世界中(請參閱Camera.unproject()
變體 )。 這可能是最簡單的。
或者,要修復相機,請參閱“ 更改LibGDX中的坐標系(Java) ”或libgdx論壇上的這篇文章 。 基本上你定義一個自定義相機,然后設置SpriteBatch
使用它而不是默認值:
// Create a full-screen camera:
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// Set it to an orthographic projection with "y down" (the first boolean parameter)
camera.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.update();
// Create a full screen sprite renderer and use the above camera
batch = new SpriteBatch(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.setProjectionMatrix(camera.combined);
在固定相機工作時,它“向上游游泳”了一下。 您將遇到其他渲染器( ShapeRenderer
,字體渲染器等),這些渲染器也會默認為“錯誤”的相機,需要修復。
我有同樣的問題,我只是這樣做。
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
screenY = (int) (gheight - screenY);
return true;
}
每次你想從用戶那里獲取輸入時都不要使用Gdx.input.getY(); 而是使用(Gdx.graphics.getHeight() - Gdx.input.getY())對我有用。
以下鏈接討論了此問題。
您需要使用方法project(Vector3 worldCoords)
類com.badlogic.gdx.graphics.Camera
。
private Camera camera;
............
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
創建向量的實例並使用輸入事件處理程序的坐標對其進行初始化。
Vector3 worldCoors = new Vector3(screenX, screenY, 0);
將世界空間中給出的worldCoors投影到屏幕坐標。
camera.project(worldCoors);
使用投影坐標。
world.hitPoint((int) worldCoors.x, (int) worldCoors.y);
OnTouch();
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.