Unity-角色控制器

角色控制器是什么?

角色控制器是让角色可以受制于碰撞 但是不会被刚体所牵制

如果我们对角色使用刚体判断碰撞,可能会出现一些奇怪的表现

比如:

  1. 在斜坡上往下滑动

  2. 不加约束的情况碰撞可能让自己被撞飞

    等等

    而角色控制器会让角色表现的更加稳定

    Unity 提供了角色控制器脚本专门用于控制角色

注意:

添加角色控制器后,不用再添加刚体

能检测碰撞函数

能检测触发器函数

能被射线检测

Slope Limit坡度度数限制,大于该值的斜坡上不去

Step Offset:台阶偏移值,单位为米,低于这个值的台阶才能上去,该值不能大于角色控制器的高度

Skin Width:皮肤的宽度,两个碰撞体可以穿透彼此最大的皮肤宽度,较大的值可以减少抖动,较小的值可能导致角色卡住,建议设置为半径的 10%

MinMoveDistance:最小移动距离,大多数情况下为 0,可以用来减少抖动

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

public class lesson19 : MonoBehaviour
{

    private Animator animator;
    private CharacterController cc;
    private float h;
    private float v;
    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
        cc = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        h = Input.GetAxis("Horizontal");
        v = Input.GetAxis("Vertical");
        //判断是否接触地面
          if (cc.isGrounded)
          {
        print("接触地面");
          }
        animator.SetFloat("x", h);
        animator.SetFloat("y", v);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            animator.SetTrigger("New Trigger");
        }
        //受重力作用的移动
        //cc.SimpleMove(transform.forward * v * 180 * Time.deltaTime);
        cc.SimpleMove(new Vector3(h, 0, v) * 3);
        //不受重力影响的移动
        //cc.Move();
    }
    //碰撞到其他对象触发
    private void OnControllerColliderHit(ControllerColliderHit hit)
    {
        print(hit.collider.gameObject.name);
    }

    private void OnTriggerEnter(Collider other)
    {
        print("触发器触发");
    }
}
相关推荐
toponad几秒前
Unity Ads Bidding 现已正式加入TopOn 聚合平台
unity·topon
小羊先生car3 小时前
RTOS-F429-HAL-(动/静态)任务的创建(2026/7/27)
开发语言·算法·c#
unityのkiven3 小时前
Unity UGUI 实战:动态生成任务面板
unity·游戏引擎
2401_859506243 小时前
珠宝玉石加工的智能化改造:AI视觉检测、3D建模与区块链溯源实践
人工智能·3d·视觉检测
地球驾驶员4 小时前
NX二次开发C#-获取体的外表面
开发语言·c#
a1117764 小时前
3D 建筑编辑器 Pascal Editor THreeJS 开源
前端·3d·html
郝学胜-神的一滴4 小时前
中级OpenGL教程 026:Assimp库从编译到实战全攻略
c++·unity·游戏引擎·图形渲染·unreal engine·opengl
向夏威夷 梦断明暄5 小时前
从 Bun 的 Rust 重写,看 C# 如何重建 AI 基础设施层
人工智能·rust·c#
心平气和量大福大5 小时前
C#-WPF-控件-LiveChart图表-线性2(LineSeries)-数据绑定
开发语言·c#·wpf
a11177618 小时前
坦克大战3D Three.js 3D (开源项目)
开发语言·javascript·3d