如何在opengl(android平台)中的特定位置(比如1.0,2.0,0.5)绘制一个对象(球体或三角形)

时间:2011-05-17 10:58:05

标签: opengl-es

我是opengl(Android平台)的新手。我想画一个opengl对象说3D中特定loaction的球体。我该怎么做?绘制后,我想在触摸事件上旋转它。所以我怎么能做这两件事?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您使用转换矩阵来执行此操作。 你需要三个矩阵来做你想做的事情,一个物体矩阵(赋予它位置和旋转),一个摄像机矩阵(给出摄像机位置和空间方向),以及一个投影矩阵(导致透视,即远东很小,很大)事情就在附近。)

在android中,你做:

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(),这些只会引起悲伤和刺激。

注意上面的代码包含perspective()函数。我怀疑它在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
}

我希望这会有所帮助......