using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(PlayerInput))] public class PlayerMovement : MonoBehaviour { public PlayerData data; new Rigidbody rigidbody; Vector2 moveInput; Vector3 moveDirection; Transform camTransform; void Awake() { rigidbody = GetComponent(); var playerInput = GetComponent(); playerInput.actions["Move"].started += OnMove; playerInput.actions["Move"].performed += OnMove; playerInput.actions["Move"].canceled += OnMove; if (Camera.main != null) camTransform = Camera.main.transform; else Debug.LogError("Couldn't find the main camera."); } void Update() { Vector3 camForward = camTransform.forward; camForward.y = 0; camForward.Normalize(); moveDirection = camForward * moveInput.y + camTransform.right * moveInput.x; } void FixedUpdate() { if (moveDirection != Vector3.zero) { rigidbody.MovePosition(rigidbody.position + moveDirection * data.speed * Time.fixedDeltaTime); AlignGroundedRotation(); } } void AlignGroundedRotation() { Quaternion goalRot = Quaternion.LookRotation(moveDirection); Quaternion slerp = Quaternion.Slerp(transform.rotation, goalRot, data.turnSpeed * moveDirection.magnitude * Time.fixedDeltaTime); transform.rotation = slerp; } void OnMove(InputAction.CallbackContext ctx) { Vector2 input = ctx.ReadValue(); if (input.sqrMagnitude > 1f) input.Normalize(); moveInput = input; } }