diff options
Diffstat (limited to 'Assets/Scripts/PlayerLocomotion.cs')
| -rw-r--r-- | Assets/Scripts/PlayerLocomotion.cs | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/Assets/Scripts/PlayerLocomotion.cs b/Assets/Scripts/PlayerLocomotion.cs new file mode 100644 index 0000000..686595d --- /dev/null +++ b/Assets/Scripts/PlayerLocomotion.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using Unity.Mathematics; +using UnityEngine; + + +namespace DS +{ + public class PlayerLocomotion : MonoBehaviour + { + private Transform _cameraObject; //存储Camera的位置 + private InputHandler _inputHandler; + private Vector3 _moveDirection; + + [HideInInspector] public Transform myTransform; + [HideInInspector] public AnimatorHandler animatorHandler; + + public new Rigidbody rigidbody; + public GameObject normalCamera; //引用Camera + + + [Header("Stats")] + [SerializeField] private float movementSpeed = 5; + [SerializeField] private float rotationSpeed = 10; + private void Start() + { + rigidbody = GetComponent<Rigidbody>(); + _inputHandler = GetComponent<InputHandler>(); + animatorHandler = GetComponentInChildren<AnimatorHandler>(); + _cameraObject = Camera.main.transform; + myTransform = transform; + animatorHandler.Initialize(); + } + + private void Update() + { + float delta = Time.deltaTime; + _inputHandler.TickInput(delta); + + _moveDirection = _cameraObject.forward * _inputHandler.vertical; + _moveDirection += _cameraObject.right * _inputHandler.horizontal; + _moveDirection.Normalize(); + + float speed = movementSpeed; + _moveDirection *= speed; + + Vector3 projectedVelocity = Vector3.ProjectOnPlane(_moveDirection, _normalVector); + rigidbody.velocity = projectedVelocity; + + animatorHandler.UpdateAnimatorValues(_inputHandler.moveAmount,0); + + if (animatorHandler.canRotate) + { + HandleRotation(delta); + } + } + + #region Movement + + private Vector3 _normalVector; + private Vector3 _targetPosition; + + private void HandleRotation(float delta) + { + Vector3 targetDir = Vector3.zero; + float moveOverride = _inputHandler.moveAmount; + + targetDir = _cameraObject.forward * _inputHandler.vertical; + targetDir += _cameraObject.right * _inputHandler.horizontal; + + targetDir.Normalize(); + targetDir.y = 0; + + if (targetDir == Vector3.zero) + { + targetDir = myTransform.forward; + } + + float rs = rotationSpeed; + Quaternion tr = Quaternion.LookRotation(targetDir); + Quaternion targetRotation = Quaternion.Slerp(myTransform.rotation, tr, rs * delta); + + myTransform.rotation = targetRotation; + } + + + #endregion + } +} + |
