这是我的游戏循环的简化版本,概述了每帧我要做的事情以及结构。所示的更新方法是通过View#onDraw方法调用的。
public static void update(Canvas canvas, GameView view){
//time operations (calculating delta etc.)
long cTime = System.currentTimeMillis();
delta = cTime - time;
time = cTime;
globals.put("time", time);
globals.put("delta", delta);//set vars for scripts
camera.applyToCanvas(canvas);//apply camera matrix to canvas
if(map != null)map.update();
if(battle != null)map.update();
Effect.updateAll();//update everything (game logic)
render.load(canvas);//load the canvas into my custom render engine
render();//call render method (shown below)
view.invalidate();//reset view for redraw
}
public static void render(){
render.reset();//clears the canvas using canvas.setColor(Color.BLACK)
if(map != null)map.draw();
if(battle != null)battle.draw();
if(dialog != null)dialog.draw();
if(gui != null)gui.draw(); //draw everything using the renderengine
}
正如您所看到的,这些操作会更新游戏组件(地图、战斗、GUI等),然后将它们呈现在屏幕上。通过查看代码,很明显我正在同一个线程上运行这些操作,因此这个线程显然不能被阻塞(否则游戏将停止)。
这就是我的问题所在。我在游戏中使用了一些按钮的GUI。这些按钮分配给8个整数(0-8),例如,当按下向上按钮时,输入数据就会通过游戏传递到现有对话框或战斗中,或者其他需要数据的地方。这些按钮依赖于主活动的触摸事件,其中MotionEvent由于从onDraw方法上的游戏循环运行,因此在与游戏本身相同的线程上运行。以下是我处理对话框的方式:
I use javascript (rhino parser) as follows (passing a dialog object to the script in the variable 'dialog'): var d = dialog.show("Hello! How are you.");
To get the input, I call the getInput method which takes in the dialog, and up to 4 strings as selection options. This method is supposed to return an integer value. This can be called through the script as follows:
var response = dialog.getInput(d, "I'm fine, thank you!", "Who wants to know.");
The getInput method is as follows in my Dialog class:
public static int getInput(Dialog d, String... args){ d.waitingForInput = true; d.lastInput = -1; while(d.waitingForInput || d.lastInput == -1){ //render options //main thread is obviously blocked here. } return d.getLastInput();//returns the d.lastInput and resets waitingForInput and lastInput. The script can then use this value to decide what to do. }
如果对我在这个问题中想要问什么有任何疑问,请留下评论,因为我已经很累了,花了一些时间来解决这个问题。
编辑:我考虑过在单独的线程上运行输入,但这仍然会导致阻止调用其他输入方法(例如更改对话框中选定的选项)。