2016-06-20 38 views
-1

如何拖動紋理(圖像)而不使其跳躍並將其自身居中放置在鼠標光標上(我在下面的代碼中)?拖動紋理(無跳轉)

當我點擊紋理時,什麼都不應該發生,當我拖動時,鼠標光標應該保持原位(相對於紋理的邊緣)。

例子:https://s31.postimg.org/ojapwbj6j/Untitled_1.jpg

SpriteBatch batch; 
Texture texture; 
OrthographicCamera camera; 
Vector3 spritePosition = new Vector3(); 

float offsetX, offsetY; 
Vector3 input; 

@Override 
public void create() { 

    batch = new SpriteBatch(); 
    texture = new Texture("badlogic.jpg"); 
    camera = new OrthographicCamera(); 
    camera.setToOrtho(false); 

} 

@Override 
public void render() { 
    Gdx.gl.glClearColor(1, 0, 0, 1); 
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 
    batch.begin(); 
    batch.draw(texture, spritePosition.x, spritePosition.y); 
    batch.end(); 

    if (Gdx.input.justTouched()){ 

      int x1 = Gdx.input.getX(); 
      int y1 = Gdx.input.getY(); 
      input = new Vector3(x1, y1, 0); 
      camera.unproject(input); 

      offsetX = x1 - spritePosition.x; 
      offsetY = y1 - spritePosition.y; 

    } 

    if (Gdx.input.isTouched()) { 

     spritePosition.set(Gdx.input.getX() - offsetX, Gdx.input.getY() - offsetY, 0); 

    } 

} 

回答

0

你需要做的是制定出相對於圖像鼠標位置的偏移量,減去,而不是一半,你在做寬/高是什麼此時此刻。

下面是一些很粗糙的僞代碼,以顯示我的意思 - 你需要重寫如Java ...

if Gdx.input.justTouched { 
    get mouse position from Gdx.input 
    camera.unproject it into cameraX and cameraY 
    offsetX = cameraX - imageX 
    offsetY = cameraY - imageY 
} 

if Gdx.input.isTouched { 
    spritePisition.set(Gdx.input.getX() - offsetX, Gdx.input.getY - offsetY) 
} 
+0

我編輯我的代碼,以配合您的答案。但我得到的結果的一半:)請檢查此更新的gif:https://s31.postimg.org/lg8nu0u2z/Animation.gif – Beckham

+0

y軸是倒置的,因爲物理座標系不同於邏輯座標(一個y和其他的y-up)。要麼使用camera.unproject(應該修復它),要麼從屏幕高度減去最終的y位置,以便有效地反轉它。 –

0

你爲什麼要使用camera.unproject?

試試這個:

Override 
public void render() { 
    Gdx.gl.glClearColor(1, 0, 0, 1); 
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 

    batch.setProjectionMatrix(camera.combined); 
    batch.begin(); 
    batch.draw(texture, spritePosition.x, spritePosition.y); 
    batch.end(); 

    if (Gdx.input.isTouched()) { 
     spritePosition.set(Gdx.input.getX() - texture.getWidth()/2, Gdx.input.getY() + texture.getHeight()/2, 0); 
    } 

} 
+0

鼠標的位置是在物理(即屏幕像素)座標,所以他應該使用相機。無法將其轉化爲邏輯座標。 –

+0

即使他從不移動相機? – IronMonkey

+0

是的。不同的座標系統。 –