CharacterMovement2D.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. private float speed = 0f;
  15. private bool isSprinting = false;
  16. private Animator anim;
  17. private Vector2 input;
  18. private float velocity;
  19. private bool headingleft = false;
  20. private Quaternion targetrot;
  21. private 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. // Update is called once per frame
  30. void FixedUpdate ()
  31. {
  32. input.x = Input.GetAxis("Horizontal");
  33. // Check if direction changes
  34. if ((input.x < 0f && !headingleft) || (input.x > 0f && headingleft))
  35. {
  36. if (input.x < 0f) targetrot = Quaternion.Euler(0, 270, 0);
  37. if (input.x > 0f) targetrot = Quaternion.Euler(0, 90, 0);
  38. headingleft = !headingleft;
  39. }
  40. // Rotate player if direction changes
  41. transform.rotation = Quaternion.Lerp(transform.rotation, targetrot, Time.deltaTime * 20f);
  42. // set speed to horizontal inputs
  43. speed = Mathf.Abs(input.x);
  44. speed = Mathf.SmoothDamp(anim.GetFloat("Speed"), speed, ref velocity, 0.1f);
  45. anim.SetFloat("Speed", speed);
  46. // set sprinting
  47. if ((Input.GetKeyDown(sprintJoystick) || Input.GetKeyDown(sprintKeyboard))&& input != Vector2.zero) isSprinting = true;
  48. if ((Input.GetKeyUp(sprintJoystick) || Input.GetKeyUp(sprintKeyboard))|| input == Vector2.zero) isSprinting = false;
  49. anim.SetBool("isSprinting", isSprinting);
  50. // Jump
  51. if ((Input.GetKeyDown(jumpJoystick) || Input.GetKeyDown(jumpKeyboard)) && isGrounded())
  52. {
  53. rigbody.velocity = new Vector3(input.x, jumpVelocity, 0f);
  54. }
  55. }
  56. public bool isGrounded()
  57. {
  58. if (checkGroundForJump)
  59. return Physics.Raycast(transform.position, Vector3.down, groundTolerance);
  60. else
  61. return true;
  62. }
  63. }
  64. }