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); // 调试信息:打印碰撞对象的名称
    }
}
相关推荐
我的offer在哪里15 小时前
示例 Unity 项目结构(Playable Game Template)
unity·游戏引擎
淡海水17 小时前
【节点】[Branch节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·branch
在路上看风景17 小时前
4.6 显存和缓存
unity
Zik----20 小时前
简单的Unity漫游场景搭建
unity·游戏引擎
在路上看风景1 天前
4.5 顶点和片元
unity
在路上看风景2 天前
31. Unity 异步加载的底层细节
unity
天人合一peng2 天前
Unity中做表头时像work中整个调整宽窄
unity
小李也疯狂2 天前
Unity 中的立方体贴图(Cubemaps)
unity·游戏引擎·贴图·cubemap
牛掰是怎么形成的2 天前
Unity材质贴图引用陷阱:包体暴涨真相
unity·材质·贴图
呆呆敲代码的小Y2 天前
【Unity工具篇】| 超实用工具LuBan,快速上手使用
游戏·unity·游戏引擎·unity插件·luban·免费游戏·游戏配置表