How to correctly rotate and move a 3D perspective camera in LibGDX

主宰稳场 提交于 2019-12-08 12:25:00

问题


I have been trying on and off now for a few weeks to correctly handle object and camera rotation in LibGDX.

I have the below move and yrotate methods in a custom class for my objects, 'this' being a ModelInstance:

public void move(float i) {
    // TODO Auto-generated method stub
    this.instance.transform.translate(0, 0, i);
    this.instance.calculateTransforms();

}

public void yrotate(float i) {
    // TODO Auto-generated method stub
    this.instance.transform.rotate(Vector3.Y, -i);
    this.instance.calculateTransforms();

}

This all seems to work fine as I can rotate objects and move them in the rotated direction correctly (though I must admit I'm a bit stumped as to why the Y Vector has to be negative).

I am now trying to replicate this for the camera. I can see that the camera also has a lot of methods available to it but they do not exactly match those used for objects. At the moment I am doing the following for the camera:

void move(float i) {
    // cam.translate(0, 0, i);
    cam.position.add(0, 0, i);
    cam.update();

}

void yrotate(float i) {
    cam.rotate(Vector3.Y, -i);
    // cam.direction.rotate(Vector3.Y, -i);
    cam.update();
}

The above seems to rotate and move the camera. However, when moving the camera the position x, y and z is not taken into consideration the rotation that has been applied.

I am thinking that for the objects it's the 'calculateTransforms' bit that does the magic here in making sure the object moves in the direction it's facing, but I'm struggling to find anything like this for the camera.

Any help would be greatly appreciated!


回答1:


If you want to move the camera into the direction it is looking into, then you can do that something like this:

private final Vector3 tmpV = new Vector3();
void move(float amount) {
    cam.position.add(tmpV.set(cam.direction).scl(amount));
    cam.update();
}

If you for some reason don't like to add a temporary vector then you can scale the vector inline:

void move(float a) {
    cam.position.add(cam.direction.x * a, cam.direction.y * a, cam.direction.z * a);
    cam.update();
}

Btw, you shouldn't call calculateTransforms if you didn't modify the nodes. See also the documentation:

This method can be used to recalculate all transforms if any of the Node's local properties (translation, rotation, scale) was modified.



来源:https://stackoverflow.com/questions/38777884/how-to-correctly-rotate-and-move-a-3d-perspective-camera-in-libgdx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!