Global Game Jam 2021
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.2 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.InputSystem;
  5. [RequireComponent(typeof(CharacterController))]
  6. public class PlayerInputController : InputBehaviour
  7. {
  8. [SerializeField]
  9. private float m_playerSpeed = 1;
  10. [SerializeField]
  11. private float m_rotationSpeed = 1;
  12. [SerializeField]
  13. [Tooltip("Used to spin on spot\n"
  14. + "0 = back\n"
  15. + "0.5 = left/right\n"
  16. + "1.0 = forward")]
  17. private AnimationCurve m_turnRadius;
  18. private CharacterController m_controller;
  19. private Vector3 m_desiredDirection;
  20. private bool m_recievedInput => m_desiredDirection.magnitude != 0;
  21. private void Awake()
  22. {
  23. m_controller = GetComponent<CharacterController>();
  24. }
  25. private void Update()
  26. {
  27. ApplyRotation();
  28. ApplyMovement();
  29. LockAxis(Vector3.up);
  30. }
  31. private void OnMovement(InputAction.CallbackContext value)
  32. {
  33. Vector2 m_recievedInput = value.ReadValue<Vector2>();
  34. m_desiredDirection = new Vector3(m_recievedInput.x, 0.0f, m_recievedInput.y);
  35. }
  36. private void ApplyRotation()
  37. {
  38. transform.forward = Vector3.Slerp(transform.forward, m_desiredDirection.normalized, m_rotationSpeed * Time.deltaTime);
  39. }
  40. private void ApplyMovement()
  41. {
  42. if (!m_recievedInput)
  43. return;
  44. float forwardRatio = (Vector3.Dot(transform.forward, m_desiredDirection.normalized) + 1) / 2;
  45. float speed = m_turnRadius.Evaluate(forwardRatio) * m_playerSpeed;
  46. m_controller.Move(transform.forward * speed * Time.deltaTime);
  47. }
  48. private void LockAxis(Vector3 axis)
  49. {
  50. transform.position = Vector3.ProjectOnPlane(transform.position, axis);
  51. }
  52. public override void RegisterInput(PlayerInput playerInput)
  53. {
  54. playerInput.currentActionMap.FindAction("Movement").performed += OnMovement;
  55. playerInput.currentActionMap.FindAction("Movement").canceled += OnMovement;
  56. }
  57. public override void UnregisterInput(PlayerInput playerInput)
  58. {
  59. playerInput.currentActionMap.FindAction("Movement").performed -= OnMovement;
  60. playerInput.currentActionMap.FindAction("Movement").canceled -= OnMovement;
  61. }
  62. }