我有一个主要活动,在相应的XML布局中,我有一个自定义视图,用于绘制游戏对象(我的坦克和10个敌人),一些按钮来控制我的坦克和射击子弹,一个TextView来显示我的分数。我的自定义视图是GameSurfaceView java类,它是半屏游戏板。 以下是我的一些代码:
public class GameSurfaceView extends SurfaceView implements Runnable {
private static Context gContext;
public GameSurfaceView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
resume();
gContext = context;
}
public void resume() {
isRunning = true;
gameThread = new Thread(this);
gameThread.start();
}
public void pause() {
isRunning = false;
boolean retry = true;
while (retry) {
try {
gameThread.join();
retry = false;
} catch (InterruptedException e) {
// try again shutting down the thread
}
}
}
@Override
public void run() {
while (isRunning) {
// We need to make sure that the surface is ready
if (!holder.getSurface().isValid()) {
continue;
}
long started = System.currentTimeMillis();
// update
step();
// draw
Canvas canvas = holder.lockCanvas();
if (canvas != null) {
render(canvas);
holder.unlockCanvasAndPost(canvas);
}
//detect all possible collisions
detectCollisions();
float deltaTime = (System.currentTimeMillis() - started);
int sleepTime = (int) (FRAME_PERIOD - deltaTime);
if (sleepTime > 0) {
try {
gameThread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
while (sleepTime < 0) {
step();
sleepTime += FRAME_PERIOD;
}
}
}
//Called from MainActivity
public void dispatchKey(int tDirection) {
Toast.makeText(gContext, "Hi", Toast.LENGTH_LONG).show();
gameStarted = true;
if (tDirection == FIRE)
Fire();
else if (tDirection != tank.Direction)
turnTankDirection = tDirection;
}
private void detectCollisions() {
//Collision Detection between tank and enemy
Toast.makeText(gContext, "Collision", Toast.LENGTH_LONG).show();
}
}
我的问题: 1-为什么dispatchKey()中的Toast正确运行但是detectCollisions()中的Toast使力关闭? 2-如何在detectCollisions()方法中更新TextView? 3-如何在detectCollisions()方法中检测到碰撞时显示DialogAlert? 我的问题主要涉及gContext变量。 感谢。
答案 0 :(得分:0)
关于问题1:也许这会影响第二个帖子。从Activity调用dispatchKey()时,将从sureface-thread调用detectCollision()。你试过从活动中调用detectCollision()吗?
关于问题3:让你的活动实现一个监听器,如果检测到冲突,将调用该监听器。你可以用同样的东西作为问题1和2的解决方案。
你应该尝试:
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
//Make toast or manipulate TextView
}
});