今天,又是充满希望的一天!

UnitySir - 00001_制作一个简陋的角色控制器

Posted on By Zj

需要实现的功能

实现角色的站立行走


知识点

Animator动画控制器的使用、行为混合树的使用

public static float Atan2 (float y, float x);

以弧度为单位计算并返回y/x反正切值

Atan2 区间范围在 [-π,π] 之间 , π = 180°

1° = π/180° 1 rad = 180°/π

弧度转角度【弧度 * (180°/π)】

角度转弧度【角度 * (π/180°)】

1弧度 ≈ 57°

1°≈0.0174533弧度

public static float Rad2Deg ;

弧度到度换算常量(只读)。

Vector3.normalized

获取向量的方向(归一化、单位向量)

public static float SmoothDampAngle (float current, float target, ref float currentVelocity, float smoothTime)

随时间推移将以度为单位给定的角度逐渐改变为所需目标角度。

Vector3.magnitude

求向量的长度(大小、向量的模)

public static float Sqrt (float f);

返回 f 的平方根。


完整代码

移动

using UnityEngine;

public class SimpleMove : MonoBehaviour
{
    private Rigidbody _rigidbody;

    [Header("角色方向控制变量")] [SerializeField] private Vector2 moveDir = Vector2.zero;
    [SerializeField] private Vector2 moveDirNormalized = Vector2.zero;
    [SerializeField] private float targetDir = 0f; //角色目标方向
    [SerializeField] private float walkSpeed = 2f; //行走速度
    private float _smoothTime = 0.1f;
    private float _currentVelocity = 0f;
    private float _vMove = 0f;
    private float _hMove = 0f;
    
    [Header("键盘输入控制")] [SerializeField] private KeyCode keyA = KeyCode.LeftShift;
    [SerializeField] private KeyCode keyB = KeyCode.None;
    [SerializeField] private KeyCode keyC = KeyCode.None;
    [SerializeField] private KeyCode keyD = KeyCode.None;

    private void Awake()
    {
        _rigidbody = GameObject.Find("MainPlayer").GetComponent<Rigidbody>();
    }

    private void Update()
    {
        _hMove = Input.GetAxis("Horizontal");
        _vMove = Input.GetAxis("Vertical");
        SetMoveDir();
        SimpleMsgMechanism.SendMsg("PlayerMove", Mathf.Sqrt(_hMove * _hMove + _vMove * _vMove));
    }

    private void FixedUpdate()
    {
        PlayerMove();
    }

    /// <summary>
    /// 设置朝向
    /// </summary>
    void SetMoveDir()
    {
        moveDir = new Vector2(_hMove, _vMove); //获取到输入的值
        moveDirNormalized = moveDir.normalized; //将值归一化(获取方向)
        targetDir = Mathf.Atan2(moveDirNormalized.x, moveDirNormalized.y) * Mathf.Rad2Deg; //计算朝向目标的角度
        if (moveDirNormalized != Vector2.zero) //当输入的值不为0时,转向目标角度
        {
            _rigidbody.transform.eulerAngles =
                Vector3.up * Mathf.SmoothDampAngle(_rigidbody.transform.eulerAngles.y, targetDir,
                    ref _currentVelocity, _smoothTime);
        }
    }

    /// <summary>
    /// 角色移动
    /// </summary>
    void PlayerMove()
    {
        _rigidbody.velocity = new Vector3(walkSpeed * _hMove, _rigidbody.velocity.y, walkSpeed * _vMove);
    }
}

参考链接

unity第三人称控制器教程


如果内容对你有所帮助:

UnitySir (bilibili)

B站ID:UnitySir