2016-02-18 59 views
3

我用LibGDX创建了一个2D安卓游戏,我使用正射相机在世界各地移动。LibGDX:用触摸移动相机

为了移动相机,玩家应该触摸并拖动屏幕。所以如果你触摸屏幕并向右拖动,相机应该向左移动。所以它应该像移动画廊中缩放图片的部分一样。我希望你跟着我。

这是代码:

public class CameraTestMain extends ApplicationAdapter { 

    SpriteBatch batch; 
    Texture img; 
    OrthographicCamera camera; 

    @Override 
    public void create() { 
     batch = new SpriteBatch(); 
     img = new Texture("badlogic.jpg"); 
     camera = new OrthographicCamera(1280, 720); 
     camera.update(); 
    } 

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

     handleInput(); 
     camera.update(); 

     batch.setProjectionMatrix(camera.combined); 

     batch.begin(); 
     batch.draw(img, 0, 0); 
     batch.end(); 
    } 

    public void handleInput() { 

     // That is my problem 

    } 

} 

我不知道该怎么在handleInput()方法写。我知道有一个名为InputProcessor的界面,方法为touchDragged(int x, int y, int pointer),您可以在其中处理触摸拖动,但我不知道如何使用它。

感谢您的想法和您的帮助。

回答

1

InputProcessor是一个界面,允许您定义在执行某些操作(如触摸屏)时要执行的操作。

所以第一件事就是实现你的类接口:

public class CameraTestMain extends ApplicationAdapter implements InputProcessor 

然后创建()方法通过调用设置类为InputProcessor:

//create() method 
    Gdx.input.setInputProcessor(this); 

第二个是实施touchDragged的方法。请注意,这是Xÿ参数只是相对去年指针位置因此要获得指针的实际位置,你应该将它保存在一些全局变量着陆方法。当然你不需要这里的绝对指针位置,因为你只需要修改摄像头的位置而不是设置它。

//touchDragged method 
    public boolean touchDragged(int screenX, int screenY, int pointer) { 
     camera.position.set(camera.position.x + screenX, camera.position.y + screenY); 

记得拨打camera.update()开始渲染()方法

为了获得更多的信息,看看at this tutorial

+0

@ erik4thewinners接受这个答案,如果它帮助你并考虑upvoting它,因为我认为这是一个很好的答案。 – Madmenyo

+0

screenX和screenY参数是绝对值。 – Winter

+2

这个答案是错误的,因为'camera.position.set(camera.position.x + screenX,camera.position。y + screenY);'由于screenX和screenY返回鼠标在屏幕上的位置,所以发送相机飞行...而不是screenX,应该放入某种“X中的变化”,并且相同的Y .. 。 – Sierox

3

这个问题是旧的,但正如Sierox说,接受的答案将发送相机飞走,所以这里的另一个解决方案

Gdx.input.getDeltaX()将返回的区别当前指针位置和X轴上的最后一个指针位置。

Gdx.input.getDeltaY()将返回当前指针位置和Y轴上最后一个指针位置之间的差异。

@Override 
public boolean touchDragged(int screenX, int screenY, int pointer) { 
    float x = Gdx.input.getDeltaX(); 
    float y = Gdx.input.getDeltaY(); 

    camera.translate(-x,y); 
    return true; 
}