ThirdPersonUserControl.cs 2.6 KB

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