How can I draw an object (sphere or triangle) in a specific place (say 1.0,2.0,0.5) in opengl (Android platform)

I am new to opengl (Android platform). I want to draw an opengl object that will say a sphere at a specific resolution in 3D. How should I do it? After drawing, I want to rotate it to a touch event.So How can I do these two things? Thanks in advance.

+3
source share
1 answer

For this you use transformation matrices. You need three matrices to do what you want, the object matrix (giving its position and rotation), the camera matrix (giving the camera position and orientation in space) and the projection matrix (which causes perspective, i.e. far from small, big things nearby).

:

float[] model = new float[16];
float[] camera = new float[16];
float[] projection = new float[16];
// those are the "basic" matrices

float[] modelview = new float[16];
float[] mvp = new float[16];
// those are their products

float f_scene_rotation_x = 10, f_scene_rotation_y = 30;
Matrix.setIdentityM(camera, 0);
Matrix.translateM(camera, 0, 0, 0, -2.5f);
Matrix.rotateM(camera, 0, f_scene_rotation_y, 1, 0, 0);
Matrix.rotateM(camera, 0, f_scene_rotation_x, 0, 1, 0);
// set up a camera, orbitting the scene

Matrix.setIdentityM(model, 0);
Matrix.translateM(model, 0, 1, 2, 0.5f); // set your desired position for the object (1.0,2.0,0.5)
//Matrix.rotateM(model, 0, angle, axisX, axisY, axisZ); // can rotate you object by defined angle arround defined axis
// set up model matrix

int mWidth = 640, mHeight = 480; // display dimensions
perspective(projection, 0, 90, (float)mWidth / mHeight, .1f, 1000.0f);
// set up perspective projection

Matrix.multiplyMM(modelview, 0, camera, 0, model, 0); // modelview = camera * model
Matrix.multiplyMM(mvp, 0, projection, 0, modelview, 0); // mvp = projection * modelview
// fuse matrices together

GLES20.glUseProgram(xxx); // bind your shader
GLES20.glUniformMatrix4fv(yyy, 1, false, GLES20.GL_FALSE, mvp); // pass the final matrix to the shader
// xxx is your program object, yyy is location of the modelview-projection matrix uniform inside your vertex shader

, OpenGL ES 2.0. , glLoadMatrix() ( mvp). OpenGL ES 1.0 glRotatef()/glTranslatef(), .

, (). , - Android, :

public static void perspective(float[] matrix, int moffset, float f_fov, float f_aspect, float f_near, float f_far)
{
    float f_w, f_h;

    f_h = (float)(Math.tan(f_fov * Math.PI / 180 * .5f)) * f_near;
    f_w = f_h * f_aspect;
    // calc half width of frustum in x-y plane at z = f_near

    Matrix.frustumM(matrix, moffset, -f_w, f_w, -f_h, f_h, f_near, f_far);
    // set frustum
}

, ...

0