PlayerMovement.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using UnityEngine;
  2. using UnityEngine.InputSystem;
  3. public class PlayerMovement : MonoBehaviour
  4. {
  5. [Header("Movement Settings")]
  6. public float moveSpeed = 5f;
  7. public float rotationSpeed = 10f;
  8. private Vector2 moveInput;
  9. private PlayerInput playerInput;
  10. private Rigidbody rb;
  11. void Awake()
  12. {
  13. playerInput = GetComponent<PlayerInput>();
  14. }
  15. void Start()
  16. {
  17. rb = GetComponent<Rigidbody>();
  18. }
  19. public void OnMove(InputAction.CallbackContext context)
  20. {
  21. moveInput = context.ReadValue<Vector2>();
  22. }
  23. void FixedUpdate()
  24. {
  25. HandleMovement();
  26. }
  27. void HandleMovement()
  28. {
  29. if (moveInput.magnitude > 0.1f)
  30. {
  31. Vector3 movement = new Vector3(moveInput.x, 0, moveInput.y) * moveSpeed;
  32. rb.linearVelocity = new Vector3(movement.x, rb.linearVelocity.y, movement.z);
  33. Vector3 lookDirection = new Vector3(moveInput.x, 0, moveInput.y);
  34. if (lookDirection != Vector3.zero)
  35. {
  36. Quaternion targetRotation = Quaternion.LookRotation(lookDirection);
  37. transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
  38. }
  39. }
  40. }
  41. }