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

Unity中角色斜向与横竖移动速度不一致问题求助

Unity角色斜向移动速度异常的解决方法

你的核心问题出在输入检测逻辑错误和速度调整思路的不合理性,下面逐一拆解并给出修正方案:

问题根源

  1. 错误使用Input.GetKeyDown:这个方法仅在按键按下的第一帧返回true,后续帧会立刻返回false,导致fMove、rMove很快被重置为false,速度调整逻辑只能在按键按下瞬间生效,无法持续。
  2. 速度赋值笔误:代码里speed = 7.07f; speed = 2.0f;直接覆盖了速度值,这是明显的错误。
  3. 手动调整速度的思路冗余:不需要用布尔变量判断移动方向,直接对移动向量做归一化处理,就能保证任何方向的移动速度一致。

最优修正方案:向量归一化

直接通过向量归一化保证移动速度统一,这是Unity处理角色移动的标准做法:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player_Movement : MonoBehaviour
{
    public float speed = 10.0f;
    public float jumpHeight = 4.0f;
    private float rightInput;
    private float forwardInput;
    private float jumpInput;

    void Update()
    {
        // 获取玩家输入
        rightInput = Input.GetAxis("Horizontal");
        forwardInput = Input.GetAxis("Vertical");
        jumpInput = Input.GetAxis("Jump");

        // 构建三维移动向量(忽略Y轴,由跳跃单独处理)
        Vector3 moveDirection = new Vector3(rightInput, 0, forwardInput);
        
        // 归一化向量:当斜向移动时,向量长度会大于1,归一化后长度强制为1,保证速度一致
        // 加入长度判断是为了避免无输入时除以0的错误
        if (moveDirection.magnitude > 1)
        {
            moveDirection.Normalize();
        }

        // 应用移动逻辑
        transform.Translate(moveDirection * speed * Time.deltaTime);
        // 单独处理跳跃
        transform.Translate(Vector3.up * jumpHeight * Time.deltaTime * jumpInput);
    }
}

如果你坚持用原布尔变量思路(不推荐)

只需修正输入检测逻辑,把Input.GetKeyDown改为Input.GetKey(检测按键是否持续按住):

// 修正后的fMove、rMove赋值逻辑
fMove = Input.GetKey("w") || Input.GetKey("s");
rMove = Input.GetKey("a") || Input.GetKey("d");

// 调整速度(去掉重复赋值)
if(fMove && rMove)
{
    speed = 7.07f;
    Debug.Log("move = " + speed);
}
else
{
    speed = 10.0f;
    Debug.Log("move = " + speed);
}

这种方式不如向量归一化优雅,因为Input.GetAxis自带输入平滑过渡,和Input.GetKey的检测逻辑可能出现不同步的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:00:51