unity 中的 CharacterController 角色控制器

以下是一个Unity C#脚本示例,该脚本展示了如何使用CharacterController组件的常用操作,包括移动角色、检测碰撞以及处理重力。

cs 复制代码
using UnityEngine;

public class CharacterControllerExample : MonoBehaviour
{
    public float speed = 6.0f; // 角色的移动速度
    public float gravity = -9.81f; // 重力加速度
    public float jumpSpeed = 8.0f; // 角色的跳跃速度

    private CharacterController characterController; // 角色控制器组件
    private Vector3 velocity = Vector3.zero; // 角色的速度
    private bool isGrounded = false; // 角色是否接触地面

    void Start()
    {
        characterController = GetComponent<CharacterController>(); // 获取角色控制器组件
    }

    void Update()
    {
        // 处理角色移动
        float moveHorizontal = Input.GetAxis("Horizontal"); // 获取水平输入(A/D或左/右箭头键)
        float moveVertical = Input.GetAxis("Vertical"); // 获取垂直输入(W/S或上/下箭头键)

        Vector3 move = new Vector3(moveHorizontal, 0.0f, moveVertical); // 创建移动方向向量
        move = move.normalized * speed * Time.deltaTime; // 归一化并乘以速度和时间增量

        // 如果按下空格键并且角色接触地面,则进行跳跃
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = jumpSpeed;
        }

        // 应用重力
        velocity.y += gravity * Time.deltaTime;

        // 使用CharacterController的Move方法移动角色
        characterController.Move(move + velocity * Time.deltaTime);

        // 检查角色是否接触地面
        isGrounded = characterController.isGrounded;

        // 重置垂直速度(防止角色在空中继续受重力影响时速度累积)
        if (isGrounded)
        {
            velocity.y = 0.0f;
        }
    }

    // 可选:处理碰撞(如果需要的话)
    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        // 这里可以添加处理碰撞的逻辑,例如播放音效、改变动画等
        // Debug.Log("Hit: " + hit.gameObject.name); // 调试信息:打印碰撞对象的名称
    }
}
相关推荐
淡海水7 小时前
16-02-C#常用数据结构源码-附录B-源码索引速查
unity·c#·游戏引擎·il2cpp
速易达网络9 小时前
无人机远程操控仿真
游戏引擎·cocos2d
郝学胜-神的一滴9 小时前
游戏引擎原理与实践 02:揭开3A游戏背后的技术面纱
开发语言·计算机网络·程序人生·游戏·游戏引擎
警醒与鞭策17 小时前
【无标题】
android·unity·性能优化·游戏引擎·perforce
zhchyun200819 小时前
【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(10)
ui·unity·游戏引擎
地狱为王1 天前
Unity使用NVIDIA的Audio2Face驱动口型
unity·游戏引擎
ebiobiz1 天前
STM32F4 Unity 单元测试与多次测试失败率统计详细步骤
stm32·unity·单元测试
一线灵1 天前
跨平台游戏引擎 Axmol-2.11.5 发布
游戏引擎·lua
淡海水1 天前
16-01-C#数据结构源码-附录A-术语表
unity·c#·游戏引擎·il2cpp
淡海水1 天前
16-03-C#数据结构源码-附录C-参考资源
unity·c#·游戏引擎·il2cpp