Search code examples
androidopengl-esrotationtouch3d-modelling

How to create 3D rotation effect in Android OpenGL?


I am currently working on a 3D model viewer for Android using OpenGL-ES. I want to create a rotation effect according to the gesture given. I know how to do single-axis rotation, such as rotate solely on the x-, y- or z-axis. However, my problem is that I don't know how to combine them all 3 together and have my app know in which axis I want to rotate depending on the touch gesture. Gestures I have in mind were:

  • Swipe up/down for x-axis
  • Swipe left/right for y-axis
  • swipe in circular motion for z-axis

How can I do this?

EDIT: I found out that 3 types of swipes can make the moment very ugly. Therefore what I did was remove the z-axis motion. After removing that condition, I found that the other 2 work really well in conjunction with the same algorithm.


Solution

  • It sounds like what you are looking to do is more math intensive than you might know. There are two ways to do this mathematically. (1) using quaternions (2) using basic linear algebra (but will result in gimbal lock if you arent careful.. but since you are just spinning then this is not a concern to you).. Lets go the second route since its easier.. What you need to do is recieve the beginning and end points of the swipe via a gesture implement and when you have those two points.. calculate the line that it makes. When you have that line, you can easily find the perpendicular vector to that line with high school math. That should now be your axis of rotation in your rotation matrix:

        //Rotate around the axis based on the rotation matrix (rotation, x, y, z)
        gl.glRotatef(rot, 1.0f, 1.0f, 0.0f);
    

    No need for the Z rotation since you can not rotate in the Z plane with a 2D tablet. The 1.0f, 1.0f are the values that should be variables that represent the x,y of your vector. The (rot) should serve as the magnitude of the distance between the two points.

    I havent done this in a while so let me know if you need more precision.