我有一个包含地形图顶点高度的数组。 当我第一次绘制地形时,它看起来不错:
但是当我沿着 z 轴旋转它时,形状的一部分似乎投影到背面的顶点后面:
90 度旋转(z 轴):
~180 度旋转(z 轴):
除了我的 map 实现之外,我的代码相当简单:
顶点着色器:
attribute vec4 position;
attribute vec4 color;
uniform mat4 matrix;
varying vec4 interpolated_color;
void main() {
gl_Position = matrix * position;
interpolated_color = color;
}
fragment 着色器:
precision mediump float;
varying vec4 interpolated_color;
void main(){
gl_FragColor = interpolated_color;
}
渲染器:
public class MapRenderer implements GLSurfaceView.Renderer {
...
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glClearColor(1.0f, 0.0f,0.0f, 1.0f);
map = mapGen.composeMap(); //gets array with vertices heights
mapView = new MapView(context, map, mapGen);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0, 0, width, height);
float aspect_ratio = (float) width/height;
Matrix.perspectiveM(projectionMatrix, 0, 45, aspect_ratio, 1f, 10f);
}
@Override
public void onDrawFrame(GL10 gl) {
float[] scratch = new float[16];
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
Matrix.setIdentityM(modelMatrix, 0);
Matrix.translateM(modelMatrix, 0, 0, 0, -4);
Matrix.rotateM(modelMatrix, 0, -cameraAngle, 1, 0, 0); //cameraAngle initialized at 0 changes with user input
Matrix.rotateM(modelMatrix, 0, mapAngle, 0, 0, 1); //mapAngle initialized at 0 changes with user input
Matrix.multiplyMM(scratch, 0, projectionMatrix, 0, modelMatrix, 0);
mapView.draw(scratch);
}
}
map View 类:
public void draw(float[] mvpMatrix){
int matrix = GLES20.glGetUniformLocation(program, "matrix");
GLES20.glUniformMatrix4fv(matrix, 1, false, mvpMatrix, 0);
//nFaces and facesBuffer are class variables
GLES20.glDrawElements(GLES20.GL_TRIANGLES, nFaces*3, GLES20.GL_UNSIGNED_SHORT, facesBuffer);
}
我尝试打开和关闭面部剔除以查看是否发生任何差异,但没有任何差异。
除了改变错误开始发生的角度之外,改变投影矩阵似乎也没有任何影响。当使用Matrix.perspectiveM
时,它似乎发生在~90度和高达~270度处,而当使用Matrix.orthoM
时,它恰好发生在90度和270度处。
我还检查了 OpenGL 是否通过 glGetErrors()
方法返回了任何错误,但没有得到任何结果。
我的顶点在缓冲区中按顺序排序,从位于 (-1, 1, 0) 的顶点到位于 (1, -1, 0) 的最后一个顶点。我不知道这是否会导致此问题,或者即使是这种情况,我如何在 OpenGL ES 2 中解决此问题以支持沿 z 轴的旋转。
最佳答案
需要启用深度测试,以便 OpenGL 考虑距离。
在渲染器上:
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glClearColor(1.0f, 0.0f,0.0f, 1.0f);
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
map = mapGen.composeMap(); //gets array with vertices heights
mapView = new MapView(context, map, mapGen);
}
关于android - OpenGL ES 2 投影切换前景和背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60908504/