简体   繁体   中英

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM