我知道以下问题在不同的论坛上被问过很多次,但是在查看了不同的解决方案后,它仍然没有解决我的问题,或者也许我没有明白他们的意思
我正在尝试在 iPhone 上使用 OpenGL ES 2.0 建立金字塔模型。
我想允许用户使用触摸屏旋转这个金字塔,这样他就可以查看形状的每个面。
我正在使用自己的矩阵实用程序,其灵感来自于书中给出的库 OpenGL ES 2.0 Programming Guide .
我有一个简单的顶点着色器,它需要 2 个制服和 2 个属性。
这是我的顶点着色器:
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
attribute vec4 vertex;
attribute vec4 color;
varying vec4 colorVarying;
void main()
{
colorVarying = color;
gl_Position = projectionMatrix * modelViewMatrix * vertex;
}
因此,在渲染过程中,我创建了 2 个矩阵:modelView 和投影矩阵。
这是我的投影矩阵的初始化方式:
[pMatrix frustumWithAngleOfView:70.0f
ratio:(float)backingWidth / (float)backingHeight
zNear:1.0f
zFar:100.0f];
[program use];
glUniformMatrix4fv(unif_projectionMatrix, 1, GL_FALSE, pMatrix.vertices);
[program unuse];
我的金字塔顶点设置如下:
GLfloat pyramid[] = {
//Base
-1.0, -1.0, 1.0, 1.0,
-1.0, -1.0, -1.0, 1.0,
1.0, -1.0, -1.0, 1.0,
1.0, -1.0, 1.0, 1.0,
//Front face
0.0, 1.0, 0.0, 1.0,
-1.0, -1.0, 1.0, 1.0,
1.0, -1.0, 1.0, 1.0,
//Right face
0.0, 1.0, 0.0, 1.0,
1.0, -1.0, 1.0, 1.0,
1.0, -1.0, -1.0, 1.0,
//Back face
0.0, 1.0, 0.0, 1.0,
1.0, -1.0, -1.0, 1.0,
-1.0, -1.0, -1.0, 1.0,
//Left face
0.0, 1.0, 0.0, 1.0,
-1.0, -1.0, -1.0, 1.0,
-1.0, -1.0, 1.0, 1.0
};
最后,这是我的绘图代码:
[EAGLContext setCurrentContext:context];
glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer);
glViewport(0, 0, backingWidth, backingHeight);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Use shader program
[program use];
// Apply transformations on the ModelView matrix
[mvMatrix identity];
[mvMatrix translateX:0 Y:0 Z:-6.0];
[mvMatrix rotateX:rotatex Y:rotatey Z:rotatez];
// Set the ModelView matrix uniform in the v-shader
glUniformMatrix4fv(unif_modelViewMatrix, 1, GL_FALSE, mvMatrix.vertices);
// Set the vertex attribute in the v-shader
glVertexAttribPointer(attr_vertex, 4, GL_FLOAT, GL_FALSE, 0, pyramid);
glEnableVertexAttribArray(attr_vertex);
// Draw
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDrawArrays(GL_TRIANGLES, 4, 3);
glDrawArrays(GL_TRIANGLES, 7, 3);
glDrawArrays(GL_TRIANGLES, 10, 3);
glDrawArrays(GL_TRIANGLES, 13, 3);
glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER];
一切似乎都工作正常,我的金字塔在这里,在 Z 轴上向后平移。
当我开始旋转形状时,问题就出现了,它看起来像是围绕用户旋转,而不是围绕自身旋转。
例如,当我从左到右触摸屏幕时,我看到金字塔在右边缘离开屏幕,然后从左边缘回到屏幕,就好像它绕着我转了一圈:页。
我对我的矩阵管理代码非常确定,所以我决定不将其发布在这里,以避免这个问题中有太多代码。有需要的话我可以给。
你知道我做错了什么吗?
非常感谢!
汤姆
最佳答案
听起来问题出在矩阵管理代码中 - 具体来说,更新mvMatrix
(modelViewMatrix)的代码实际上是在改变projectionMatrix
。
关于iphone - OpenGL ES 2.0 : Object rotation problem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2966996/