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

如何修复Lua/Love2D中斜向移动速度快于正常移动的问题?

斜向移动速度过快的修复方案

斜向移动时速度变快的核心原因是:同时按下横向和纵向按键时,x、y轴各自叠加速度,合成后的实际移动速度是单轴速度的√2倍(约1.414倍),导致移动更快。

修复思路是先计算输入的方向向量,再对向量进行归一化处理,确保无论哪个方向移动,最终的速度大小一致。

修改后的代码如下:

function love.update(dt)
    -- 初始化方向向量
    local dx = 0
    local dy = 0

    -- 根据按键更新方向
    if love.keyboard.isDown("w") then dy = dy - 1 end
    if love.keyboard.isDown("s") then dy = dy + 1 end
    if love.keyboard.isDown("d") then dx = dx + 1 end
    if love.keyboard.isDown("a") then dx = dx - 1 end

    -- 归一化方向向量,避免斜向速度异常
    local length = math.sqrt(dx*dx + dy*dy)
    if length > 0 then
        dx = dx / length
        dy = dy / length
    end

    -- 应用移动
    player.x = player.x + dx * 75 * dt
    player.y = player.y + dy * 75 * dt
end

代码说明

  • 先通过按键输入得到x、y轴的方向分量dx和dy
  • 计算方向向量的长度,若长度大于0(即有移动输入),将dx和dy除以长度,得到长度为1的单位向量
  • 最后用单位向量乘以设定的速度值和dt,保证任何方向的移动速度都一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:33:23