unity TopDown角色移动控制

本文档介绍了一个Unity中的角色控制器实现,包括角色根据鼠标方向朝向、八方向移动以及walk、run、sprint三种移动状态的切换。通过Input.GetAxis获取用户输入,结合Animator进行不同速度的移动动画播放,实现平滑的角色移动效果。

角色看向鼠标方向
角色保持世界坐标移动
角色八方向移动动画
idle ,走路,跑步,冲刺切换

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

namespace Game
{
   
   
    public class CharacterController : MonoBehaviour
    {
   
   
        float inputX;
        float inputY;
        Vector2 centerScreenPos;
        [Tooltip("加速度")]
        public float vel_Speed=10f;
        Transform mTransfrom;
        public float rotateSpeed = 1000;
        private static int VEL_X = Animator.StringToHash("VelX");
        private static int VEL_Z = Animator.StringToHash("VelZ");
        Animator Animator;

        public enum moveType
        {
   
   
            walk,
            run,
            sprint,
        }
        public moveType currentMoveType = moveType.walk;

        private void Awake()
        {
   
   
            Animator = GetComponent<Animator>();
            centerScreenPos = new Vector2(Screen.width / 2.0f, Screen.height / 2.0f);
            mTransfrom = transform;
        }

        private void Update()
        {
   
   
            inputX = Input.GetAxis("Horizontal");
            inputY = Input.GetAxis("Vertical");

            Locomotion();
        }

        private void Locomotion()
        {
   
   
            //角色朝向鼠标
            Vector2 mousePos = Input.mousePosition;
            Vector2 dir = mousePos - centerScreenPos;
            //计算角度
            float angle = VectorAngle(dir, Vector2.up);


            //Quaternion targetQua = Quaternion.LookRotation(new Vector3(dir.x, 0, dir.y));
            //mTransfrom.rotation = Quaternion.RotateTowards(mTransfrom.rotation, targetQua, 1000 * Time.deltaTime);

            float moveX = 0;
            float moveZ = 0;
            float targerAngle = 0;
            float moveSpeed = 0.5f;//walk
            switch (currentMoveType)
            {
   
   
                case moveType.walk:
                    break;
                case moveType.run:
                    moveSpeed = 0.8f;
                    break;
                case moveType.sprint:
                    moveSpeed = 1f;
                    break;
                default:
                    break;
            }
            

            #region 方向判断
            if (angle > -22.5 && angle <= 22.5)
            {
   
   
                //1              
                targerAngle =</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值