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

Unity中FPS角色斜向移动加速问题及速度测量咨询

问题解答

一、斜向移动加速的原因

是,完全是因为同时输入两个方向导致速度叠加。当你同时按下水平和垂直方向键时,x和z的输入值都会达到±1,此时计算出的move向量是transform.right ± transform.forward,这个向量的模长是√(1²+1²)≈1.414,相当于把原来的speed放大了1.4倍,所以角色斜向移动时速度会比单方向快。

二、测量每帧移动的单位速度

有两种可靠的实现方式:

方式1:通过位置差计算

利用每帧的位置变化除以帧时间,得到角色实际移动速度,这种方法不受CharacterController内部逻辑干扰:

// 在类中保存上一帧的位置
private Vector3 lastFramePosition;

void Start()
{
    Controller = GetComponent<CharacterController>();
    lastFramePosition = transform.position;
}

void Update()
{
    // ... 你的其他移动逻辑代码 ...

    // 计算每帧移动速度
    Vector3 currentPosition = transform.position;
    Vector3 frameDelta = currentPosition - lastFramePosition;
    float frameSpeed = frameDelta.magnitude / Time.deltaTime;
    // 若只关心地面移动速度,剔除y轴分量
    float groundSpeed = new Vector3(frameDelta.x, 0, frameDelta.z).magnitude / Time.deltaTime;
    
    Debug.Log("当前帧总移动速度:" + frameSpeed);
    Debug.Log("当前帧地面移动速度:" + groundSpeed);

    lastFramePosition = currentPosition;
}

方式2:直接使用CharacterController的velocity属性

CharacterController.velocity是Unity提供的角色当前移动速度向量,取它的模长即可得到速度值;如果只需要地面移动速度,要剔除y轴的重力/跳跃分量:

// 在Update方法中添加
float totalSpeed = Controller.velocity.magnitude;
float groundSpeed = new Vector3(Controller.velocity.x, 0, Controller.velocity.z).magnitude;
Debug.Log("总移动速度:" + totalSpeed);
Debug.Log("地面移动速度:" + groundSpeed);

修复斜向移动加速的方法

对move向量做归一化处理,确保无论单方向还是斜向移动,向量模长始终为1,这样速度就不会被放大。注意要跳过角色静止的情况(避免除以0的错误):

float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");

Vector3 move = transform.right * x + transform.forward * z;
// 用小阈值规避浮点精度问题,仅在有输入时归一化
if (move.magnitude > 0.1f)
{
    move = move.normalized;
}

Controller.Move(move * speed * Time.deltaTime);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:37:44