我正在编写一个简单的2D游戏引擎。我已经决定了引擎的工作方式:它将由包含“事件”的对象组成,这些事件将在适当时触发我的主游戏循环。
有关结构的更多信息:每个GameObject
都有updateEvent
方法。objectList
是将接收更新事件的所有对象的列表。仅此列表上的对象具有由游戏循环调用的updateEvent方法。
我正在尝试在GameObject类中实现此方法(该规范正是我想要实现的方法:[]):/**
* This method removes a GameObject from objectList. The GameObject
* should immediately stop executing code, that is, absolutely no more
* code inside update events will be executed for the removed game object.
* If necessary, control should transfer to the game loop.
* @param go The GameObject to be removed
*/
public void remove(GameObject go)
因此,如果对象试图在更新事件中删除自身,则控件应转移回游戏引擎:
public void updateEvent() {
//object's update event
remove(this);
System.out.println("Should never reach here!");
}
这是我到目前为止的内容。它可以工作,但是我对使用异常进行流控制的了解越少,我就越不喜欢它,所以我想看看是否有替代方法。
删除方法
public void remove(GameObject go) {
//add to removedList
//flag as removed
//throw an exception if removing self from inside an updateEvent
}
游戏循环
for(GameObject go : objectList) {
try {
if (!go.removed) {
go.updateEvent();
} else {
//object is scheduled to be removed, do nothing
}
} catch(ObjectRemovedException e) {
//control has been transferred back to the game loop
//no need to do anything here
}
}
// now remove the objects that are in removedList from objectList
2个问题:
是
[编辑]