[英]java libgdx move perspective camera
我正在創建一個3D游戲,但我不知道如何根據我的手指翻譯相機。 我正在創建一個地圖(x = -30到+30; y = -30到30; z = -1到1),其中每個坐標用於使用我的資產中的.g3db文件的模型,並使用模型放置到位翻譯。 這項工作到目前為止,地圖看起來很好,並以67%的角度查看。 地圖太大,無法立即在相機中查看(不,我不想縮小)。 每當我觸摸我的Android手機的屏幕時,它只是圍繞中心旋轉,而是我希望游戲地圖從我的視角保持原位,而是改變透視攝像機在x和y軸上的位置。 沒有可用於位置跟蹤的游戲對象,一切都應該取決於我的手指動作。 這樣我想要移動到每個x和y方向的可見屏幕(想象它看起來像2D攝像機向上,向下和向前移動到圖片前面)。 你能幫助我嗎?
到目前為止這是我的代碼:
public class MyGdxGame extends ApplicationAdapter implements ApplicationListener{
//define variables
...
@Override
public void create() {
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
modelBatch = new ModelBatch();
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(10f, 10f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
assets = new AssetManager();
//load assets
...
loading = true;
camController = new CameraInputController(cam);
camController.forwardTarget = true;
Gdx.input.setInputProcessor(camController);
}
private void doneLoading() {
//load models and add them to instances
loading = false
}
@Override
public void render() {
if (loading && assets.update())
doneLoading();
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
modelBatch.render(instances, environment);
modelBatch.end();
}
我使用Spring工具套件3.5.1作為IDE和libgdx 1.0.1
不要使用CameraInputController
,而是實現InputProcessor並在調用Gdx.input.setInputProcessor
使用該類。
例如:
public class MyGdxGame extends ApplicationAdapter implements InputProcessor {
並在創建方法:
Gdx.input.setInputProcessor(this);
除了需要額外代碼的touchDown
和touchDragged
方法之外,您必須實現此鏈接中顯示的所有方法:
private int dragX, dragY;
@Override
public boolean touchDown (int x, int y, int pointer, int button) {
dragX = x;
dragY = y;
return true;
}
@Override
public boolean touchDragged (int x, int y, int pointer) {
float dX = (float)(x-dragX)/(float)Gdx.graphics.getWidth();
float dY = (float)(dragY-y)/(float)Gdx.graphics.getHeight();
dragX = x;
dragY = y;
cam.position.add(dX * 10f, dY * 10f, 0f);
cam.update();
return true;
}
這里dX
和dY
值是用戶在-1f
和+1f
之間的范圍-1f
屏幕上拖動的量。 例如,對於dX
,值為0.5f
意味着用戶將屏幕尺寸的一半拖到右側。 請注意,這些是自上次調用方法以來的delta值。 每次拖動操作可能會多次調用該方法。 因此, dX
和dY
將是小值。
對cam.position.add(...)
的調用實際上會將攝像頭和調用移動到cam.update();
將重新計算渲染所需的值。 我已經使用了10f
的乘數來進行相機的X和Y平移。 這意味着如果用戶完全從屏幕的左邊緣拖動到右邊緣,則相機將向右移動總共10個單位。 您可以根據需要調整值。
請注意,這會將相機移動到XY平面上。 如果需要移動,例如XZ平面,則需要相應地調整cam.position.add(...)
的調用。 此外,這不會改變相機的方向。 如果你想移動相機,同時查看相同的位置,你需要添加cam.lookAt(0,0,0);
就在cam.update();
之前cam.update();
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.