开发者

Rotating in OpenGL relative to the viewport

I'm trying t开发者_如何学运维o display an object in the view which can be rotated naturally by dragging the cursor/touchscreen. At the moment I've got X and Y rotation of an object like this

glRotatef(rotateX, 0f, 1f, 0f); // Dragging along X, so spin around Y axis
glRotatef(rotateY, 1f, 0f, 0f);

I understand why this doesn't do what I want it to do (e.g. if you spin it right 180 degrees, up and down spinning gets reversed). I just can't figure out a way for both directions to stay left-right and up-down relative to the viewer.

I can assume that the camera is fixed and looking along the Z axis. Any ideas?


Your best bet is to implement a Quaternion-based rotation. In the Quaternion world, every time you rotate, it will be axis-aligned to the axis you specify, without being affected by the previous rotations. This is also why it doesn't suffer from Gimbal Lock.

I've found these pages helpful for implementing quaternions:

  • http://en.wikipedia.org/wiki/Quaternion
  • http://www.cprogramming.com/tutorial/3d/quaternions.html
  • http://www.gamedev.net/reference/articles/article1095.asp

Good luck. I'm sure there are other solutions, but this one is one of the cleanest you can have.


Solved it! Add xAngle and yAngle to the current matrix.

Matrix.rotateM(matrix, 0, xAngleADD, matrix[1], matrix[5], matrix[9]);
Matrix.rotateM(matrix, 0, yAngleADD, matrix[0], matrix[4], matrix[8]);
gl.glMultMatrixf(matrix, 0);


I decided to put my DragControl class up for download, along with the Quaternion support class. Once you have an OpenGL canvas looking along the Z axis at some object, it should be little effort to drop this in. It's just the plain .java files currently, no built library.

DragControl handles pretty much everything including finger flinging, so you can send your object spinning with a flick.

http://github.com/halfninja/android-dragcontrol3d

In activity setup:

dragControl = new DragControl();
glView.setOnTouchListener(dragControl);

When updating object rotation in a loop:

Quaternion rotation = dragControl.currentRotation();

If you make any cool modifications I'd like to see them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜