简体   繁体   English

如何在JavaFX中实现游戏的控制系统?

[英]How do I implement a control system for a game in JavaFX?

I am trying to create a control system for my simple 2D game using javaFX. 我正在尝试使用javaFX为我的简单2D游戏创建一个控制系统。 I did extensive research and was unable to come up with anything. 我进行了广泛的研究,无能为力。

What I want to do: I want to set a series of special key events to control a ship and to bring up a pause menu. 我想做什么:我想设置一系列特殊按键事件来控制飞船并调出暂停菜单。 When I was trying to get a pause menu to display using something similar to this 当我尝试使用类似于此的东西来显示暂停菜单时

gameScene.setOnKeyPressed(new EventHandler<KeyEvent>() {
        public void handle(KeyEvent e) {
            if (e.equals(KeyCode.P) {

            }
        }
    }); 

I get a "The method setOnKeyPressed(EventHandler) in the type Scene is not applicable for the arguments (new EventHandler(){})" warning in reference to the type argument of EventHandler. 我在引用EventHandler的类型参数时收到“场景类型的setOnKeyPressed(EventHandler)方法不适用于参数(new EventHandler(){})”的警告。 I have seen examples of this expression being used in this exact way. 我已经看到了以这种确切方式使用该表达式的示例。 I want 'P' to be the key to pull up the pause menu. 我希望“ P”成为拉起暂停菜单的关键。 I am unsure why I receive this error. 我不确定为什么会收到此错误。 On a side vote I am wondering what method I should call to display a Scene or Pane? 顺带一提,我想知道应该使用哪种方法来显示“场景”或“窗格”?

The way I have done it is having the onKeyPressed set on the Root Pane of the Scene. 我这样做的方法是在场景的根窗格上设置onKeyPressed。

So something like 所以像

BorderPane root = new BorderPane();
root.setOnKeyPressed((KeyEvent e) -> {
    if (e.getCode().equals(KeyCode.P) {
        //Open Pause Menu  
    }
});

EDIT 1: Don't forget to use the root to open your scene. 编辑1:不要忘记使用根来打开您的场景。

Scene gameScene = new Scene(root);
stage.setScene(gameScene);
stage.show();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM