You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX复刻塞尔达射击小游戏:按空格投射物无法持续上移问题排查

解决JavaFX射击游戏空格键无效问题

问题根源

代码存在三个关键错误导致空格键功能失效:

  • 按键映射放错集合:创建keyCommandsBall后,误将SPACE键的moveUp命令添加到keyCommands集合,而非keyCommandsBall,导致按键事件无法找到对应的射击命令。
  • 动画循环强制重置投射物速度:AnimationTimer的handle方法中,每次循环都执行ball.setVelocity(0, 0);,直接覆盖了按下空格时设置的向上速度。
  • 多余按键映射错误:keyCommands2集合未正确赋值,反而向keyCommands中添加F19/F18的映射,属于无效操作。

修复方案

1. 修正按键映射集合

将SPACE键的命令放入正确的keyCommandsBall集合:

Map<KeyCode,Command> keyCommandsBall = new HashMap<>();
// 替换错误的keyCommands.put为keyCommandsBall.put
keyCommandsBall.put(KeyCode.SPACE, moveUp);

2. 移除投射物速度的强制重置

删除AnimationTimer中每次循环都重置投射物速度的代码,避免覆盖手动设置的速度:

AnimationTimer animation = new AnimationTimer()
{
    @Override
    public void handle(long now){
        c.setVelocity(1.0, 0);
        c2.setVelocity(1.0,0);
        c3.setVelocity(1.0,0);
        
        // 移除这行强制重置代码
        // ball.setVelocity(0, 0);
        
        rec.setVelocity(-2.0,0);
        rec2.setVelocity(-2.0,0);
        rec3.setVelocity(-2.0,0);
        rec4.setVelocity(-2.0,0);
        // ... 其余代码保持不变
    }
};

3. 修正keyCommands2的赋值(可选)

如果需要用F19/F18控制角色移动,应将映射添加到keyCommands2集合:

Map<KeyCode,Command> keyCommands2 = new HashMap<>();
keyCommands2.put(KeyCode.F19, moveLeft);
keyCommands2.put(KeyCode.F18, moveRight);

4. 优化投射物发射逻辑(可选)

若希望每次按空格发射新的投射物而非复用同一个,可修改射击命令:

Command shoot = new Command(){
    @Override
    public void execute(Sprite sprite){
        // 基于玩家位置创建新投射物
        Circle newBall = new Circle(player.getNode().getTranslateX()+35, player.getNode().getTranslateY(),5);
        Sprite ballSprite = new Sprite(newBall);
        root.getChildren().add(ballSprite.getNode());
        ballSprite.setVelocity(0,-5); // 调整为更快的向上速度
    }
};
keyCommandsBall.put(KeyCode.SPACE, shoot);

内容的提问来源于stack exchange,提问作者Hickymcmicky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:40:37