如何并排绘制两个正方形?

时间:2013-07-06 16:29:25

标签: android opengl-es

android OpenGL ES tutorial之后,我可以在屏幕上画一个正方形。

我想在屏幕上画第二个方格,在最初的方格旁边,所以我做了如下(只有两次):

Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 3.0f, 0, 0, 0, 0, 1.0f, 0);
float[] modelMatrix = new float[16];
Matrix.setIdentityM(modelMatrix, 0);
Matrix.translateM(modelMatrix, 0, 2, 2, 0); //arbitrarily picking 2, the correctly drawn square uses 0's.
Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, modelMatrix, 0)
Matrix.multiplyMM(mMVPMatrix, 0, mMVPMatrix, 0, mProjMatrix, 0);

然后继续绘制它(link to google's code

值得注意的是:

private final String vertexShaderCode =
"uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition;" +
"void main() {" +
"  gl_Position = vPosition * uMVPMatrix;" +
"}";

GLES20.glViewport(0, 0, width, height);
float ratio = (float) width / height;
Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);

然而,我的第二个方块是这样倾斜的:

enter image description here

为什么会这样?如何在不改变初始坐标的情况下简单地在此旁边画一个正方形?

我怀疑它与Matrix.setLookAtM()有关,并且投影正在重塑广场。我不确定如何解决这个问题!

1 个答案:

答案 0 :(得分:0)

This thread solved my issue.

在着色器中,我乘以

vPosition * uMVPMatrix;" 

但乘法应遵循排序:

transformed vertex = projMatrix * viewMatrix * modelMatrix * input vertex

请注意输入顶点位于投影,视图和模型矩阵(MVPMatrix)之后

所以切换到

vPosition * uMVPMatrix;

float[] pvMatrix = new float[16];
//projection * view
Matrix.multiplyMM(pvMatrix, 0, mProjMatrix, 0, mViewMatrix, 0);
float[] mModelMatrix = new float[16];
Matrix.setIdentityM(mModelMatrix, 0);
Matrix.scaleM(mModelMatrix,0, mScale[0],mScale[1], 1.0f);
Matrix.translateM(mModelMatrix, 0, mPosition[0],mPosition[1], mPosition[2]);
//projection * view * model
Matrix.multiplyMM(mMVPMatrix,0, pvMatrix, 0, mModelMatrix, 0);

诀窍!