我制作了一个简单的 android 应用程序,它使用 openGL 渲染一个正方形。可以用手指移动方 block 。它工作正常,但在四处移动方 block 时,您会感觉到相当大的输入滞后,尤其是在做圆周运动时。有什么技巧可以减少或掩盖这种滞后吗?
代码如下:
public class InputTestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new InputTestView(this));
}
public class InputTestView extends GLSurfaceView {
private InputTestRenderer renderer;
private float prevX;
private float prevY;
public InputTestView(Context context) {
super(context);
renderer = new InputTestRenderer();
setRenderer(renderer);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_MOVE:
renderer.moveEye(prevX - x, prevY -y);
case MotionEvent.ACTION_DOWN:
prevX = x;
prevY = y;
break;
}
return true;
}
}
public class InputTestRenderer implements Renderer {
private final float[] verts = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f, 0.5f, 0.5f, 0.0f };
private final int nrOfVerts = verts.length / 3;
private FloatBuffer vertBuf;
private float eyeX;
private float eyeY;
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glColor4f(1, 0, 0, 1);
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(verts.length * Float.SIZE / 8);
byteBuffer.order(ByteOrder.nativeOrder());
vertBuf = byteBuffer.asFloatBuffer();
vertBuf.put(verts);
vertBuf.position(0);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(-width / 2, width / 2, height / 2, -height / 2, 1, 100);
gl.glMatrixMode(GL10.GL_MODELVIEW);
}
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glLoadIdentity();
synchronized (this) {
gl.glTranslatef(-eyeX, -eyeY, -10);
}
gl.glScalef(200, 200, 1);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuf);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, nrOfVerts);
}
public synchronized void moveEye(float deltaX, float deltaY) {
this.eyeX += deltaX;
this.eyeY += deltaY;
}
}
}
最佳答案
怀疑您的 UI 线程和渲染线程正在争夺 CPU 时间。尝试将此行添加到 onSurfaceCreated() :
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
降低渲染器的优先级可确保运动事件得到更迅速的处理。似乎有所作为。
FWIW 我不喜欢 GLSurfaceView 的设计,更喜欢使用 Handler.postDelayed() 来安排每帧以 20 毫秒的间隔绘制每帧。
关于Android OpenGL 响应能力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8894003/