UserControlThirdPerson.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace RootMotion.Demos {
  4. /// <summary>
  5. /// User input for a third person character controller.
  6. /// </summary>
  7. public class UserControlThirdPerson : MonoBehaviour {
  8. // Input state
  9. public struct State {
  10. public Vector3 move;
  11. public Vector3 lookPos;
  12. public bool crouch;
  13. public bool jump;
  14. public int actionIndex;
  15. }
  16. public bool walkByDefault; // toggle for walking state
  17. public bool canCrouch = true;
  18. public bool canJump = true;
  19. public State state = new State(); // The current state of the user input
  20. protected Transform cam; // A reference to the main camera in the scenes transform
  21. protected virtual void Start () {
  22. // get the transform of the main camera
  23. cam = Camera.main.transform;
  24. }
  25. protected virtual void Update () {
  26. // read inputs
  27. state.crouch = canCrouch && Input.GetKey(KeyCode.C);
  28. state.jump = canJump && Input.GetButton("Jump");
  29. float h = Input.GetAxisRaw("Horizontal");
  30. float v = Input.GetAxisRaw("Vertical");
  31. // calculate move direction
  32. Vector3 move = cam.rotation * new Vector3(h, 0f, v).normalized;
  33. // Flatten move vector to the character.up plane
  34. if (move != Vector3.zero) {
  35. Vector3 normal = transform.up;
  36. Vector3.OrthoNormalize(ref normal, ref move);
  37. state.move = move;
  38. } else state.move = Vector3.zero;
  39. bool walkToggle = Input.GetKey(KeyCode.LeftShift);
  40. // We select appropriate speed based on whether we're walking by default, and whether the walk/run toggle button is pressed:
  41. float walkMultiplier = (walkByDefault ? walkToggle ? 1 : 0.5f : walkToggle ? 0.5f : 1);
  42. state.move *= walkMultiplier;
  43. // calculate the head look target position
  44. state.lookPos = transform.position + cam.forward * 100f;
  45. }
  46. }
  47. }