2013-05-13 63 views
11

我有一個呈現PNG圖像的屏幕(BaseScreen實現了屏幕界面)。點擊屏幕時,它將角色移動到觸摸的位置(用於測試目的)。渲染和觸摸輸入之間的libgdx座標系差異

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維基說明)的座標和座標觸摸輸入從左上角開始。所以我遇到的問題是我點擊右下角,它將圖像移到右上角。我的座標可能是X 675 Y 13,觸摸時會靠近屏幕的頂部。但角色顯示在底部,因爲座標從左下角開始。

爲什麼是什麼?爲什麼座標系顛倒了?我是否使用錯誤的對象來確定這一點?

回答

17

爲了檢測碰撞,我使用camera.unproject(vector3)。我設置vector3爲:

x = Gdx.input.getX();  
y = Gdx.input.getY(); 
z=0; 

現在我通過這個載體,camera.unproject(vector3)。使用此矢量的xy繪製您的角色。

+1

有很多這樣的問題在那裏,很多答案說,你需要做的camera.unproject的,但我當我與libGDX開始我根本不知道該怎麼做,然後(即使用新的矢量座標)。這是我當時發現的唯一答案,指出了這一點,非常感謝,很好的答案! – 2015-03-13 10:32:42

6

你做得對。 Libgdx通常以「原生」格式提供座標系統(在本例中爲原生觸摸屏座標,以及默認的OpenGL座標)。這不會產生任何一致性,但它確實意味着圖書館不必介入您和其他所有人之間。大多數OpenGL遊戲使用一個相對任意的「世界」座標映射到屏幕上的相機,所以世界/遊戲座標通常與屏幕座標非常不同(所以一致性是不可能的)。請參閱Changing the Coordinate System in LibGDX (Java)

有兩種方法可以解決此問題。一個是改變你的觸摸座標。另一種是使用不同的相機(不同的投影)。

修復觸摸座標,只需從屏幕高度減去y即可。這有點破解。更一般地說,你希望從屏幕上「不投射」到世界上(參見 Camera.unproject() variations)。這可能是最簡單的。

或者,至修復相機請參閱「Changing the Coordinate System in LibGDX (Java)」或this post on the libgdx forum。基本上你定義一個自定義的相機,然後設置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,字體渲染器等),它們也將默認爲「錯誤」的相機並需要修復。

4

我有同樣的問題,我只是做了這個。

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()) 爲我工作。

1

下面的鏈接討論了這個問題。

Projects the given coords in world space to screen coordinates.

您需要使用方法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); 

項目世界空間中給出的世界座標以屏幕座標。

camera.project(worldCoors); 

使用投影座標。

world.hitPoint((int) worldCoors.x, (int) worldCoors.y); 

    OnTouch(); 

    return true; 
}