简体   繁体   中英

How to Use a Quaternion to Control a Camera

I am trying to allow orbiting of a camera around a sphere in my 3D scene. I have decided to go the route of quaternions. I am having a bit of trouble understanding where to start with it though. I don't know how to set them up correctly and how to apply it to my camera. After that, I don't know how I would go about controlling the camera with a virtual joystick on the screen. I have read about quaternions a lot but most example don't give an example of how to use them in 3D programming. Any ideas?

Trying to give you a quick answer, you at the end need to covert the quaternion to a matrix so that you can use it with OpenGL ES. Use the quaternion to store you rotations, chain them and when you are ready to render your scene, get that "encoded" rotation out of the quaternion (as a matrix) and pass it as the view matrix down to your pipeline.

Check this source code for a quick quaternion class android-ready (it has a toMatrix method for your convenience):

https://github.com/TraxNet/ShadingZen/blob/master/library/src/main/java/org/traxnet/shadingzen/math/Quaternion.java

An example:

Quaternion camera_quat = new Quanternion(); // This creates an identity quaternion
camera_quat.setRotation(new Vector3(0.f, 1.f, 0.f), PI/2); // generate a 90 degrees    rotation around the given vector

float [] matrix = camera_quat.toMatrix().getAsArray();

At this point you have a rotation matrix that you can use as your view matrix.

EDIT : Are yo targeting OpengGL ES 1.x or 2.0? I can give you direction on what to do with that matrix depending on the version you are targeting. You can also take a look the ShadingZen repo for more information on OpenGL 2.0 (org.traxnet.ShadingZen.core.Camera class).

EDIT2 : One of the great things about a quaternion is that you can easily rotate around an arbitrary axis. My code above rotates around the (0,1,0). You can exploit this idea: define two quaternions, one for one joystick axis, and another one for the other axis. Multiply both quaternions and you have both rotations. Convert to matrix and viola! Hope that helps.

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