CharacterMovementNoCamera.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using UnityEngine;
  2. // WASD to move, Space to sprint
  3. public class CharacterMovementNoCamera : MonoBehaviour
  4. {
  5. public Transform InvisibleCameraOrigin;
  6. public float StrafeSpeed = 0.1f;
  7. public float TurnSpeed = 3;
  8. public float Damping = 0.2f;
  9. public float VerticalRotMin = -80;
  10. public float VerticalRotMax = 80;
  11. public KeyCode sprintJoystick = KeyCode.JoystickButton2;
  12. public KeyCode sprintKeyboard = KeyCode.Space;
  13. private bool isSprinting;
  14. private Animator anim;
  15. private float currentStrafeSpeed;
  16. private Vector2 currentVelocity;
  17. void OnEnable()
  18. {
  19. anim = GetComponent<Animator>();
  20. currentVelocity = Vector2.zero;
  21. currentStrafeSpeed = 0;
  22. isSprinting = false;
  23. }
  24. void FixedUpdate()
  25. {
  26. var input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
  27. var speed = input.y;
  28. speed = Mathf.Clamp(speed, -1f, 1f);
  29. speed = Mathf.SmoothDamp(anim.GetFloat("Speed"), speed, ref currentVelocity.y, Damping);
  30. anim.SetFloat("Speed", speed);
  31. anim.SetFloat("Direction", speed);
  32. // set sprinting
  33. isSprinting = (Input.GetKey(sprintJoystick) || Input.GetKey(sprintKeyboard)) && speed > 0;
  34. anim.SetBool("isSprinting", isSprinting);
  35. // strafing
  36. currentStrafeSpeed = Mathf.SmoothDamp(
  37. currentStrafeSpeed, input.x * StrafeSpeed, ref currentVelocity.x, Damping);
  38. transform.position += transform.TransformDirection(Vector3.right) * currentStrafeSpeed;
  39. var rotInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
  40. var rot = transform.eulerAngles;
  41. rot.y += rotInput.x * TurnSpeed;
  42. transform.rotation = Quaternion.Euler(rot);
  43. if (InvisibleCameraOrigin != null)
  44. {
  45. rot = InvisibleCameraOrigin.localRotation.eulerAngles;
  46. rot.x -= rotInput.y * TurnSpeed;
  47. if (rot.x > 180)
  48. rot.x -= 360;
  49. rot.x = Mathf.Clamp(rot.x, VerticalRotMin, VerticalRotMax);
  50. InvisibleCameraOrigin.localRotation = Quaternion.Euler(rot);
  51. }
  52. }
  53. }