Unity角色控制器CharacterController移动代码

亲测好用 角色控制器(CharacterController):

首先,角色控制器没有碰撞效果,这是和刚体的区别,不像刚体可以给其力

如果想使人物移动,直接复制官方文本中的CharacterController下的Move()方法,前台添加“CharacterController”这个组件。

using UnityEngine;
using System.Collections;
 
public class NewBehaviourScript : MonoBehaviour {
          
   
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;
 
    void Start() {
          
   
 
    }
    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);
    }
 
}

无需理解,直接复制就可以用了,前后左右移动。

参数:

Slope Limit爬坡限制:小于等于此角度可以上坡 Step Offset台阶高度: Skin Width 皮肤宽度:太大就抖动,太小就卡住,最好设置成Radius半径的10% Min Move Distance:0,太多不行,太小动不了 Center:中心点坐标 Radius:半径,一般0.5 Height:高,一般2.0

经验分享 程序员 微信小程序 职场和发展