角色控制器如何在 Unity 中添加推动刚体的功能

在本教程中,我们将增强 Unity FPS 控制器 脚本,使角色能够在场景中推动刚体(下面的脚本应该适用于任何控制器,只要它具有附加的角色控制器组件)。该脚本允许玩家与对象和动态环境进行交互,从而为您的游戏增添真实感。

第 1 步:创建一个新脚本

第 2 步:复制提供的脚本

  • 将以下代码复制到新创建的脚本中。您可以调整 'pushPower' 变量来控制推动的强度。此外,您可能需要根据游戏的逻辑自定义施加推力的条件。

角色推送控制器.cs

using UnityEngine;

public class CharacterPushController : MonoBehaviour
{
    // Adjust this variable to control the strength of the push
    public float pushPower = 2.0f;

    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Rigidbody body = hit.collider.attachedRigidbody;

        // No rigidbody or kinematic rigidbody
        if (body == null || body.isKinematic)
        {
            return;
        }

        // Avoid pushing objects below the character
        if (hit.moveDirection.y < -0.3)
        {
            return;
        }

        // Calculate push direction from move direction,
        // pushing only to the sides, not up and down
        Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);

        // Apply the push
        body.velocity = pushDir * pushPower;
    }
}

第 3 步:附加脚本

第四步:测试

  • 播放 场景并测试角色控制器在新创建的脚本的帮助下推动刚体的能力。

第五步:调整

  • 调整 和 'pushPower' 以在游戏中实现所需的行为。
推荐文章
Unity 直升机控制器
在 Unity 中向 2D 平台游戏角色控制器添加双跳支持
如何在 Unity 中进行起重机控制
Unity 汽车控制器
Unity 飞机控制器
在Unity中实现跑酷系统
在 Unity 中为 FPS 播放器添加蹲伏功能