我在libgdx中有一个平铺地图,我在课堂上实现了GestureDetector pan方法。
我想要发生的是当用户使用平移方法时,屏幕被拖动到那个方向,有点像用户用他的手指移动平铺地图。
当我在桌面上测试代码时,拖动非常精细,地图以完美的速度和平滑度拖动。
但是当我在不同的Android设备上测试相同的代码时,拖动的速度要么太慢,要么太快。有时小手指移动会将地图移动到整个屏幕上。
如何让pan方法在所有设备上保持一致?我的代码:
public class SinglePlayerGame extends GestureDetector.GestureAdapter implements Screen{
private TiledMap map;
private OrthogonalTiledMapRenderer mapRenderer;
private OrthographicCamera camera;
private Viewport viewport;
private Main game;
public SinglePlayerGame(Main game){
this.game = game;
this.camera = new OrthographicCamera();
this.viewport = new StretchViewport(Main.VIRTUAL_WIDTH, Main.VIRTUAL_HEIGHT, camera);
this.map = new TmxMapLoader().load("map_1.tmx");
this.mapRenderer = new OrthogonalTiledMapRenderer(map);
this.camera.position.set(viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2, 0);
Gdx.input.setInputProcessor(new GestureDetector(this));
resize(Main.VIRTUAL_WIDTH, Main.VIRTUAL_HEIGHT);
}
public boolean pan(float x, float y, float deltaX, float deltaY){
camera.translate(-deltaX, deltaY);
camera.update();
return false;
}
@Override
public void render(float delta){
update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
game.batch.end();
mapRenderer.render();
}
public void update(){
camera.update();
mapRenderer.setView(camera);
}
@Override
public void resize(int width, int height){
viewport.update(width, height);
}
public void show(){}
public void pause(){}
public void resume(){}
public void hide(){}
@Override
public void dispose(){
}
答案 0 :(得分:0)
GestureDetector单位为屏幕像素,因此您需要根据相机和视口的定义将它们缩放到世界单位:
public boolean pan(float x, float y, float deltaX, float deltaY){
float scaleX = viewport.getWorldWidth() / (float)viewport.getScreenWidth();
float scaleY = viewport.getWorldHeight() / (float)viewport.getScreenHeight();
camera.translate((int)(-deltaX * scaleX), (int)(deltaY * scaleY));
camera.update();
return false;
}