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); // 调试信息:打印碰撞对象的名称
    }
}
相关推荐
℡枫叶℡12 小时前
Unity - 全局配置Unity工程的资源检索的目录
unity·资源检索配置
mxwin12 小时前
Unity URP 下 TBN 矩阵学习 切线空间、tangent.w 与镜像 UV 的那些坑
学习·unity·矩阵·shader
程序猿多布12 小时前
Unity导表工具解决方案-Luban使用教程
unity·luban
mxwin12 小时前
Unity URP Shader 混合模式完全指南
unity·游戏引擎
mxwin13 小时前
Unity URP 下 HDR 与 Tonemapping 的 Shader 意识
unity·游戏引擎
沉默金鱼13 小时前
U3D高级编程:主程手记——第二章2.1读书笔记
unity·游戏引擎
mxwin1 天前
Unity Shader 深度写入与关闭ZWrite Off · 半透明排序 · 粒子穿插
unity·游戏引擎·shader
张老师带你学1 天前
宇宙飞船完整Unity项目
科技·游戏·unity·游戏引擎·模型
mxwin1 天前
Unity URP 下的流体模拟 深入解析 Navier-Stokes 方程与浅水方程的数学原理
unity·游戏引擎
mxwin1 天前
Unity Shader 深度重建世界坐标
unity·游戏引擎·shader