ThirdPersonUserControl.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using UnityEngine;
  3. using UnityStandardAssets.CrossPlatformInput;
  4. namespace UnityStandardAssets.Characters.ThirdPerson
  5. {
  6. [RequireComponent(typeof (ThirdPersonCharacter))]
  7. public class ThirdPersonUserControl : MonoBehaviour
  8. {
  9. private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object
  10. private Transform m_Cam; // A reference to the main camera in the scenes transform
  11. private Vector3 m_CamForward; // The current forward direction of the camera
  12. private Vector3 m_Move;
  13. private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input.
  14. private void Start()
  15. {
  16. // get the transform of the main camera
  17. if (Camera.main != null)
  18. {
  19. m_Cam = Camera.main.transform;
  20. }
  21. else
  22. {
  23. Debug.LogWarning(
  24. "Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
  25. // we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
  26. }
  27. // get the third person character ( this should never be null due to require component )
  28. m_Character = GetComponent<ThirdPersonCharacter>();
  29. }
  30. private void Update()
  31. {
  32. if (!m_Jump)
  33. {
  34. m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
  35. }
  36. }
  37. // Fixed update is called in sync with physics
  38. private void FixedUpdate()
  39. {
  40. // read inputs
  41. float h = CrossPlatformInputManager.GetAxis("Horizontal");
  42. float v = CrossPlatformInputManager.GetAxis("Vertical");
  43. bool crouch = Input.GetKey(KeyCode.C);
  44. // calculate move direction to pass to character
  45. if (m_Cam != null)
  46. {
  47. // calculate camera relative direction to move:
  48. m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
  49. m_Move = v*m_CamForward + h*m_Cam.right;
  50. }
  51. else
  52. {
  53. // we use world-relative directions in the case of no main camera
  54. m_Move = v*Vector3.forward + h*Vector3.right;
  55. }
  56. #if !MOBILE_INPUT
  57. // walk speed multiplier
  58. if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
  59. #endif
  60. // pass all parameters to the character control script
  61. m_Character.Move(m_Move, crouch, m_Jump);
  62. m_Jump = false;
  63. }
  64. }
  65. }