我有一个在线程中运行的gameloop,我的问题是
mGLSurfaceView.requestRender();
因空指针异常而崩溃。我的onSurfaceCreated方法中有一个日志标记,它证明表面已创建(至少我认为),所以这不是问题。
我在想问题是requestRender需要一个非静态引用。当我尝试调用对另一种方法的非静态引用时,它崩溃了。因此,我只能假设线程与非静态对象不太友好。我也不能对requestRender进行静态引用(这将是一个明显的解决方案)。
这是我的游戏循环线程
import android.util.Log;
public class GameLoop extends Thread {
private MyGLSurfaceView myGLSurfaceView;
private final static int maxFPS = 30;
private final static int maxFrameSkips = 5;
private final static int framePeriod = 1000 / maxFPS;
public static boolean running;
public final static String TAG = "input";
@Override
public void run() {
running = LaunchActivity.getRunning();
long beginTime;
long timeDiff;
int sleepTime;
int framesSkipped;
sleepTime = 0;
while (running) {
running = LaunchActivity.getRunning();
Log.d(TAG, "gameRunning");
beginTime = System.currentTimeMillis();
framesSkipped = 0;
// notice the static reference here
GameLogic.update();
Log.d(TAG, "updated");
// not static here
myGLSurfaceView.requestRender();
Log.d(TAG, "rendered");
timeDiff = System.currentTimeMillis() - beginTime;
sleepTime = (int)(framePeriod - timeDiff);
if (sleepTime > 0) {
try{
Thread.sleep(sleepTime);
Log.d(TAG, "sleeping" + String.valueOf(sleepTime));
}catch(InterruptedException e){}
}
while(sleepTime < 0 && framesSkipped < maxFrameSkips){
GameLogic.update();
sleepTime += framePeriod;
framesSkipped++;
Log.d(TAG, "Frames Skipped");
}
}
}
}
这是我的表面创建方法(虽然我可能会长期成为问题的一部分)
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glClearDepthf(1.0f);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glDepthFunc(GL10.GL_LEQUAL);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
Log.d(TAG, "SurfaceCreated");
}
哦,顺便说一句,我正在使用
glOrthof
投影
堆栈跟踪
10-05 20:26:44.694: ERROR/AndroidRuntime(18276): FATAL EXCEPTION: Thread-11
10-05 20:26:44.694: ERROR/AndroidRuntime(18276): java.lang.NullPointerException
10-05 20:26:44.694: ERROR/AndroidRuntime(18276): at basicmelon.games.androidgamething.GameLoop.run(GameLoop.java:33)
10-05 20:26:44.694: ERROR/AndroidRuntime(18276): at java.lang.Thread.run(Thread.java:1096)
日志标签
10-05 20:28:23.077: DEBUG/input(18923): GLSurfaceViewed
10-05 20:28:23.116: DEBUG/input(18923): Created
10-05 20:28:23.116: DEBUG/input(18923): Resumed
10-05 20:28:23.124: DEBUG/input(18923): gameRunning
10-05 20:28:23.132: DEBUG/input(18923): Updated
10-05 20:28:23.210: DEBUG/input(18923): Paused
最佳答案
您永远不会创建MyGLSurfaceView对象。您必须将这行代码放在while循环之前:
myGLSurfaceView = new MyGLSurfaceView();