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

Game Maker飞机移动问题:按下下键后滑行时反向移动

问题描述

我正在学习使用Game Maker,计划制作一个基础飞机移动脚本作为项目。已完成飞机移动部分,并添加了缓慢滑行停止的功能,但遇到问题:按下下箭头键时,飞机可向下移动,但滑行停止时却向上移动。

相关初始变量:

  • plane_speed = 0
  • plane_acceleration = 0.1

当前代码:

// Check keyboard input for up and down keys
keyboard_up = keyboard_check(vk_up);
keyboard_down = keyboard_check(vk_down);

// Adjust plane speed based on keyboard input and switch costumes
if keyboard_up == 1 {
    plane_speed = plane_speed + plane_acceleration;
    y -= plane_speed;  // Move plane up (assuming y is decreasing moves up)
    sprite_index = Sprite3;  // Change sprite to Sprite3 when moving up
}

if keyboard_down == 1 {
    plane_speed = plane_speed + plane_acceleration;
    y += plane_speed;  // Move plane down (assuming y is increasing moves down)
    sprite_index = sPlane;  // Change sprite to sPlane when moving down
}

if keyboard_down == 0 && keyboard_up == 0
    if plane_speed != 0 {
        if (plane_speed > 0) {
            plane_speed = plane_speed - plane_acceleration;
            y -= plane_speed;
        }
        if (plane_speed < 0) {
            plane_speed = plane_speed + plane_acceleration;
            y -= plane_speed;
        }

    }

尝试过调整加减符号,但问题反而更严重,请问这是代码顺序问题、bug还是其他原因?


问题原因与修复方案

核心问题

你的代码存在两个关键错误:

  1. 速度没有区分方向:不管按下上键还是下键,你都给plane_speed加正数的加速度,导致上下移动的速度都是正值,滑行时的方向判断完全混乱。
  2. 移动逻辑与速度更新耦合:在按键判断里直接更新位置,同时滑行阶段的y轴计算逻辑错误,导致停止时方向反转。

修复步骤

  1. 给速度赋予方向属性:
    • 上键对应y轴减小,所以应该让plane_speed增加负数(或者直接减去加速度),这样向上移动时速度为负,向下时为正。
  2. 分离速度更新与移动操作:先统一根据输入更新速度,再单独处理位置移动,避免逻辑混乱。
  3. 修正滑行阶段的移动逻辑:先根据当前速度移动,再进行减速操作,确保方向正确。

修正后的代码

// 检测按键输入
keyboard_up = keyboard_check(vk_up);
keyboard_down = keyboard_check(vk_down);

// 根据输入更新速度
if (keyboard_up) {
    plane_speed -= plane_acceleration; // 向上时速度为负
    sprite_index = Sprite3;
} else if (keyboard_down) {
    plane_speed += plane_acceleration; // 向下时速度为正
    sprite_index = sPlane;
} else {
    // 滑行减速逻辑
    if (plane_speed > 0) {
        plane_speed -= plane_acceleration;
        // 防止速度变为负数导致反向移动
        if (plane_speed < 0) plane_speed = 0;
    } else if (plane_speed < 0) {
        plane_speed += plane_acceleration;
        // 防止速度变为正数导致反向移动
        if (plane_speed > 0) plane_speed = 0;
    }
}

// 统一处理移动(根据速度方向调整y轴)
y += plane_speed;

额外优化点

  • 增加了速度边界判断(减速时避免速度正负反转),防止滑行到停止时出现微小的反向抖动。
  • 使用else if处理上下键互斥,避免同时按下两个键时速度相互抵消。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:18:21