CharacterMovement2D.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using UnityEngine;
  2. namespace Cinemachine.Examples
  3. {
  4. [AddComponentMenu("")] // Don't display in add component menu
  5. public class CharacterMovement2D : MonoBehaviour
  6. {
  7. public KeyCode sprintJoystick = KeyCode.JoystickButton2;
  8. public KeyCode jumpJoystick = KeyCode.JoystickButton0;
  9. public KeyCode sprintKeyboard = KeyCode.LeftShift;
  10. public KeyCode jumpKeyboard = KeyCode.Space;
  11. public float jumpVelocity = 7f;
  12. public float groundTolerance = 0.2f;
  13. public bool checkGroundForJump = true;
  14. float speed = 0f;
  15. bool isSprinting = false;
  16. Animator anim;
  17. Vector2 input;
  18. float velocity;
  19. bool headingleft = false;
  20. Quaternion targetrot;
  21. Rigidbody rigbody;
  22. // Use this for initialization
  23. void Start ()
  24. {
  25. anim = GetComponent<Animator>();
  26. rigbody = GetComponent<Rigidbody>();
  27. targetrot = transform.rotation;
  28. }
  29. #if ENABLE_LEGACY_INPUT_MANAGER
  30. // Update is called once per frame
  31. void FixedUpdate ()
  32. {
  33. input.x = Input.GetAxis("Horizontal");
  34. // Check if direction changes
  35. if ((input.x < 0f && !headingleft) || (input.x > 0f && headingleft))
  36. {
  37. if (input.x < 0f) targetrot = Quaternion.Euler(0, 270, 0);
  38. if (input.x > 0f) targetrot = Quaternion.Euler(0, 90, 0);
  39. headingleft = !headingleft;
  40. }
  41. // Rotate player if direction changes
  42. transform.rotation = Quaternion.Lerp(transform.rotation, targetrot, Time.deltaTime * 20f);
  43. // set speed to horizontal inputs
  44. speed = Mathf.Abs(input.x);
  45. speed = Mathf.SmoothDamp(anim.GetFloat("Speed"), speed, ref velocity, 0.1f);
  46. anim.SetFloat("Speed", speed);
  47. // set sprinting
  48. if ((Input.GetKeyDown(sprintJoystick) || Input.GetKeyDown(sprintKeyboard))&& input != Vector2.zero) isSprinting = true;
  49. if ((Input.GetKeyUp(sprintJoystick) || Input.GetKeyUp(sprintKeyboard))|| input == Vector2.zero) isSprinting = false;
  50. anim.SetBool("isSprinting", isSprinting);
  51. }
  52. #endif
  53. private void Update()
  54. {
  55. #if ENABLE_LEGACY_INPUT_MANAGER
  56. // Jump
  57. if ((Input.GetKeyDown(jumpJoystick) || Input.GetKeyDown(jumpKeyboard)))
  58. {
  59. rigbody.AddForce(new Vector3(0, jumpVelocity, 0), ForceMode.Impulse);
  60. }
  61. #else
  62. InputSystemHelper.EnableBackendsWarningMessage();
  63. #endif
  64. }
  65. public bool isGrounded()
  66. {
  67. if (checkGroundForJump)
  68. return Physics.Raycast(transform.position, Vector3.down, groundTolerance);
  69. else
  70. return true;
  71. }
  72. }
  73. }