CharacterController3rdPerson.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace RootMotion.Demos {
  4. /// <summary>
  5. /// Basic Mecanim character controller for 3rd person view.
  6. /// </summary>
  7. public class CharacterController3rdPerson: MonoBehaviour {
  8. public CameraController cam; // The camera
  9. private AnimatorController3rdPerson animatorController; // The Animator controller
  10. void Start() {
  11. animatorController = GetComponent<AnimatorController3rdPerson>();
  12. cam.enabled = false;
  13. }
  14. void LateUpdate() {
  15. // Update the camera first so we always have its final translation in the frame
  16. cam.UpdateInput();
  17. cam.UpdateTransform();
  18. // Read the input
  19. Vector3 input = inputVector;
  20. // Should the character be moving?
  21. // inputVectorRaw is required here for not starting a transition to idle on that one frame where inputVector is Vector3.zero when reversing directions.
  22. bool isMoving = inputVector != Vector3.zero || inputVectorRaw != Vector3.zero;
  23. // Character look at vector.
  24. Vector3 lookDirection = cam.transform.forward;
  25. // Aiming target
  26. Vector3 aimTarget = cam.transform.position + (lookDirection * 10f);
  27. // Move the character.
  28. animatorController.Move(input, isMoving, lookDirection, aimTarget);
  29. }
  30. // Convert the input axis to a vector
  31. private static Vector3 inputVector {
  32. get {
  33. return new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
  34. }
  35. }
  36. // Convert the raw input axis to a vector
  37. private static Vector3 inputVectorRaw {
  38. get {
  39. return new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
  40. }
  41. }
  42. }
  43. }