角色控制器 CharacterController.Move

角色控制器没有碰撞效果和刚体最明显的区别

 

属性面板参数:

Slope Limit:爬坡限制
Step Offset:台阶高度
Skin Width :皮肤厚度 皮肤厚度决定了两个碰撞器可以互相渗入的深度。较大的皮肤厚值度会导致颤抖。小的皮肤厚度值会导致角色被卡住。一个合理的设定是使该值等于半径(Radius)的10%。
Min Move Distance:最小移动距离 如果角色移动的距离小于该值,那角色就不会移动。这可以避免颤抖现象。大部分情况下该值被设为0。
Center:中心点  该值决定胶囊碰撞器在世界空间中的位置,并不影响角色的行动。
Radius:半径 胶囊碰撞器的半径长度
Height:高度 角色的胶囊碰撞器高度

 

 

调用Move方法可以实现人物移动

以下为官方代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CubePlayer : MonoBehaviour
{
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;

    void Update()
    {
        CharacterController controller = GetComponent<CharacterController>();
        //是否触碰地面
        if (controller.isGrounded)
        {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpSpeed;

        }
        moveDirection.y -= gravity * Time.deltaTime;//模拟重力
        controller.Move(moveDirection * Time.deltaTime);//移动
    }
}

 

注意的地方:

模拟重力的作用是当人物跳起或者从上往下可以落下来,不然人物不会往下走,不会触碰地面

 

 

CharacterController 是 Unity 引擎中用于控制角色移动和碰撞检测的组件,它可以非常方便地实现角色的移动和跳跃。下面是一个简单的代码示例,演示如何使用 CharacterController 实现角色的移动和跳跃: ```csharp using UnityEngine; public class PlayerController : MonoBehaviour { public float moveSpeed = 5f; // 移动速度 public float jumpSpeed = 10f; // 跳跃速度 public float gravity = 20f; // 重力加速度 private CharacterController controller; private Vector3 moveDirection = Vector3.zero; void Start() { controller = GetComponent<CharacterController>(); } void Update() { // 计算角色的移动向量 float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector3 move = transform.right * h + transform.forward * v; moveDirection = move * moveSpeed; // 判断角色是否在地面上 if (controller.isGrounded) { // 角色跳跃 if (Input.GetButtonDown("Jump")) { moveDirection.y = jumpSpeed; } } // 应用重力 moveDirection.y -= gravity * Time.deltaTime; // 使用 CharacterController 控制角色移动 controller.Move(moveDirection * Time.deltaTime); } } ``` 在这个示例中,我们首先定义了一些参数,包括移动速度、跳跃速度和重力加速度等。然后在 Start() 方法中获取 CharacterController 组件的引用。在 Update() 方法中,我们首先计算角色的移动向量,然后判断角色是否在地面上。如果在地面上,就检测是否按下了跳跃键,如果是,则将角色的垂直速度设置为跳跃速度。最后,我们应用重力,并使用 CharacterController 控制角色移动。 需要注意的是,在使用 CharacterController 控制角色移动时,我们需要将移动向量乘以 Time.deltaTime,以确保在不同的帧率下,角色的移动速度始终保持一致。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值