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

基于玩家方向与角度调整移动速度的问题排查

斜坡移动速度异常问题

当前玩家在坡度大于30度的斜面正向向上移动时,速度会降低;转向下坡时速度恢复默认值,这一表现符合预期。但倒退着在该斜面上向上移动时,速度并未降低,仍保持默认值。尝试使用Vector3.SignedAngle判断移动方向,但未能解决该问题。

原代码如下:

if (isGrounded && Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, 2f))
{
    float angle = Vector3.SignedAngle(hit.normal, Vector3.up, transform.right);
    float slopeAngle = Vector3.Angle(Vector3.up, hit.normal);

    if (slopeAngle > 30f)
    {
        if (angle < 0) // 判定为上坡
        {
            speed = 2f; // 降低速度
        }
        else
        {
            speed = 5f; // 恢复默认速度
        }
    }
    else
    {
        speed = 5f; // 默认速度
    }
}

问题分析

原代码的核心问题是:Vector3.SignedAngle(hit.normal, Vector3.up, transform.right)仅判断了斜面相对于玩家右侧的朝向,完全没有关联玩家的实际移动方向。当玩家倒退移动时,实际移动方向与transform.forward相反,但代码逻辑未考虑这一变量,导致上坡判定失效。

解决方案

需要结合玩家的实际移动方向向量来判断是否朝上坡方向移动,步骤如下:

  1. 计算斜坡的上坡方向:将斜面法线投影到水平面,推导得出斜坡的上坡方向向量。
  2. 通过点积判断玩家移动方向与上坡方向的关系:点积为正说明玩家正朝上坡移动(无论前进还是倒退),此时触发减速;反之恢复默认速度。

修正后的代码:

if (isGrounded && Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, 2f))
{
    float slopeAngle = Vector3.Angle(Vector3.up, hit.normal);
    // 替换为你实际使用的玩家世界空间移动方向(需归一化)
    Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;

    if (slopeAngle > 30f)
    {
        // 计算斜坡的上坡方向向量
        Vector3 slopeHorizontal = Vector3.Cross(hit.normal, Vector3.up);
        Vector3 slopeUphillDirection = Vector3.Cross(slopeHorizontal, hit.normal).normalized;
        
        // 点积判断移动方向是否指向上坡
        float dotProduct = Vector3.Dot(moveDirection, slopeUphillDirection);
        
        if (dotProduct > 0) // 朝上坡移动(前进/倒退均触发)
        {
            speed = 2f;
        }
        else
        {
            speed = 5f;
        }
    }
    else
    {
        speed = 5f;
    }
}

注意事项

  • moveDirection需替换为项目中实际控制玩家移动的世界空间向量(确保已经归一化处理)。
  • 通过点积判断方向关系,能覆盖所有朝向斜坡上方的移动行为,包括前进、倒退等场景,解决了原代码的逻辑漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 03:42:33