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); // 调试信息:打印碰撞对象的名称
    }
}
相关推荐
Zarek枫煜1 小时前
C3 编程语言 - 现代 C 的进化之选
c语言·开发语言·青少年编程·rust·游戏引擎
Sator15 小时前
Unity AStarPath的踩坑点
unity
榮華8 小时前
DOTA全图透视辅助下载DOTA全图科技辅助下载DOTA外挂下载魔兽争霸WAR3全图下载
数据库·科技·游戏·游戏引擎·游戏程序·ai编程·腾讯云ai代码助手
RPGMZ11 小时前
RPGMakerMZ 游戏引擎 野外采集点制作
javascript·游戏·游戏引擎·rpgmz·野外采集点
星河耀银海12 小时前
Unity基础:摄像机Camera的参数设置与视角控制
unity·游戏引擎·lucene
星河耀银海12 小时前
Unity基础:Transform组件的位移、旋转与缩放详解
unity·游戏引擎·lucene
weixin_409383121 天前
godot 击败敌人后增加经验的脚本
游戏引擎·godot
海清河晏1111 天前
数据结构 | 单链表
数据结构·unity·dreamweaver
mxwin1 天前
Unity URP 下 MatCap 技术详解 无视光照环境的卡通与质感渲染方案
unity·游戏引擎
weixin_409383121 天前
godot 获取敌人位置自动发射子弹 旋转枪口
游戏引擎·godot