我正在尝试使用JavaFX的AnimationTimer实现传统的游戏循环:
@Override
public void handle(long currentNanoTime) {
// calculate time since last update.
double elapsedTime = (currentNanoTime - lastNanoTime) / 1e9f;
lastNanoTime = currentNanoTime;
// Handle Input
switch (currentScreen) {
case AREA_ONE-> areaOneInputHandler.handle();
case AREA_TWO-> areaTwoInputHandler.handle();
}
// Update the models
areaOneUpdater.update(elapsedTime);
areaTwoUpdater.update(elapsedTime);
// Clear the canvas
gc.clearRect(0,0,InterfaceConstants.CANVAS_WIDTH,
InterfaceConstants.CANVAS_HEIGHT);
// Render
switch (currentScreen) {
case AREA_ONE -> areaOneRenderer.render();
case AREA_TWO-> areaTwoRenderer.render();
}
}
我要弄清楚的是实现handle()方法的最佳方法,因为在这种情况下,“输入”是在画布节点上触发的鼠标/键盘事件。我目前的想法是:
一个问题是handle()更新模型是否正确,还是应该完全使用update()完成。可以同时更新模型吗?
我所讨论的基本实现是:
GeneralHandler.java
public class GeneralHandler {
private MouseEvent clickMouseEvent;
// Getters and Setters omitted
}
初始化画布的位置:
canvas.setOnMouseClicked(generalHandler::setClickMouseEvent);
AreaOneInputHandler.java
public class AreaOneInputHandler extends Handler {
private AreaOneModel areaOneModel;
private GeneralHandler generalHandler;
public AreaOneInputHandler (AreaOneModel areaOneModel, GeneralHandler generalHandler) {
this.areaOneModel= areaOneModel;
this.generalHandler = generalHandler;
}
@Override
public void handle() {
if (generalHandler.getClickMouseEvent() != null) {
// Update the model
generalHandler.setClickMouseEvent(null);
}
}
}
这合适吗?这是我第一次真正尝试实现游戏循环,我想知道这是否违反了任何规范,或者是否会导致我进一步陷入困境。