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); // 调试信息:打印碰撞对象的名称
    }
}
相关推荐
微三云生态系统架构师-彭丹2 小时前
任务卷轴积分系统架构设计:从任务状态机到合规风控的完整实现
unity·系统架构·游戏引擎
XR技术研习社3 小时前
从 PICO 文档看未来短期内的 Unity 版本选择
unity·游戏引擎·xr·vr
玖玥拾6 小时前
Unity 热更新(一)
unity·游戏引擎
软件黑马王子6 小时前
1.non-MonoBehaviour 单例模式泛型基类
unity·前端框架·c#
KhalilRuan19 小时前
Unity性能优化
unity·性能优化·游戏引擎
ellis197019 小时前
u3d IMGUI[二] 编辑器扩展
unity
五仁烧饼1 天前
Unity性能优化系列内存篇 - 移动端内存优化
unity·性能优化·游戏引擎
WiChP3 天前
【V0.1B15】从零开始的2D游戏引擎开发之路
游戏引擎
zhchyun20084 天前
# 【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(06)
ui·unity·游戏引擎
Behaviour4 天前
Unity游戏HybridCLR 热更新接入实战
游戏·unity·游戏引擎