@Override public void onSurfaceChanged(GL10 gl, int width, int height) { // 设置视窗大小及位置 GLES20.glViewport(0, 0, width, height); // 计算GLSurfaceView的宽高比 float ratio = (float) width / height; // 调用此方法计算产生透视投影矩阵 MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 1, 100); // 调用此方法产生摄像机9参数位置矩阵 MatrixState.setCamera(cx, 0, cz, 0, 0, 0, 0f, 1.0f, 0.0f); }
@Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { // 设置屏幕背景色RGBA GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // 打开深度检测 GLES20.glEnable(GLES20.GL_DEPTH_TEST); MatrixState.setInitStack(); treeTextureId = initTexture(R.drawable.tree); desert = new Desert( MySurfaceView.this, new float[] { 0, 0, 0, 6, 6, 6, 6, 6, 6, 0, 0, 0 }, 30, 20); desertId = initTexture(R.drawable.desert); group = new TreeGroup(MySurfaceView.this, treeTextureId); Collections.sort(mRender.group.trees); }
@SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { x = event.getX(); y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: flag = true; new Thread() { @Override public void run() { while (flag) { if (x > 0 && x < WIDTH / 2 && y > 0 && y < HEIGHT / 2) { // 向前 Offset = Offset - 0.5f; } else if (x > WIDTH / 2 && x < WIDTH && y > 0 && y < HEIGHT / 2) { // 向后 Offset = Offset + 0.5f; } else if (x > 0 && x < WIDTH / 2 && y > HEIGHT / 2 && y < HEIGHT) { direction = direction + DEGREE_SPAN; } else if (x > WIDTH / 2 && x < WIDTH && y > HEIGHT / 2 && y < HEIGHT) { direction = direction - DEGREE_SPAN; } try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } }.start(); break; case MotionEvent.ACTION_UP: flag = false; break; } // 设置新的观察目标点XZ坐标 cx = (float) (Math.sin(direction) * Offset); // 观察目标点x坐标 cz = (float) (Math.cos(direction) * Offset); // 观察目标点z坐标 // 计算所有树的朝向 mRender.group.calculateBillboardDirection(); // 给树按照离视点的距离排序 Collections.sort(mRender.group.trees); // 设置新的摄像机位置 MatrixState.setCamera(cx, 0, cz, 0, 0, 0, 0, 1, 0); return true; }
@Override public void onDrawFrame(GL10 gl) { // 清除深度缓冲与颜色缓冲 GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); MatrixState.pushMatrix(); MatrixState.translate(0, -2, 0); desert.drawSelf(desertId); MatrixState.popMatrix(); // 开启混合 GLES20.glEnable(GLES20.GL_BLEND); // 设置混合因子 GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); MatrixState.pushMatrix(); MatrixState.translate(0, -2, 0); group.drawSelf(); MatrixState.popMatrix(); // 关闭混合 GLES20.glDisable(GLES20.GL_BLEND); }