Facebook
From UrbanMaster, 7 Years ago, written in C++.
Embed
Download Paste or View Raw
Hits: 469
  1. using System;
  2. using UnityEngine;
  3. using UnityStandardAssets.CrossPlatformInput;
  4. using UnityStandardAssets.Utility;
  5. using Random = UnityEngine.Random;
  6.  
  7. namespace UnityStandardAssets.Characters.FirstPerson
  8. {
  9.     [RequireComponent(typeof (CharacterController))]
  10.     [RequireComponent(typeof (AudioSource))]
  11.     public class FirstPersonController : MonoBehaviour
  12.     {
  13.         [SerializeField] private bool m_IsWalking;
  14.         [SerializeField] private float m_WalkSpeed;
  15.                 [SerializeField] speed = m_IsWalking ? m_WalkSpeed : m_CanRun ? m_RunSpeed : m_WalkSpeed;
  16.         [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
  17.         [SerializeField] private float m_JumpSpeed;
  18.         [SerializeField] private float m_StickToGroundForce;
  19.         [SerializeField] private float m_GravityMultiplier;
  20.         [SerializeField] private MouseLook m_MouseLook;
  21.         [SerializeField] private bool m_UseFovKick;
  22.         [SerializeField] private FOVKick m_FovKick = new FOVKick();
  23.         [SerializeField] private bool m_UseHeadBob;
  24.         [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
  25.         [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
  26.         [SerializeField] private float m_StepInterval;
  27.         [SerializeField] private AudioClip[] m_FootstepSounds;    // an array of footstep sounds that will be randomly selected from.
  28.         [SerializeField] private AudioClip m_JumpSound;           // the sound played when character leaves the ground.
  29.         [SerializeField] private AudioClip m_LandSound;           // the sound played when character touches back on ground.
  30.  
  31.         private Camera m_Camera;
  32.         private bool m_Jump;
  33.         private float m_YRotation;
  34.         private Vector2 m_Input;
  35.         private Vector3 m_MoveDir = Vector3.zero;
  36.         private CharacterController m_CharacterController;
  37.         private CollisionFlags m_CollisionFlags;
  38.         private bool m_PreviouslyGrounded;
  39.         private Vector3 m_OriginalCameraPosition;
  40.         private float m_StepCycle;
  41.         private float m_NextStep;
  42.         private bool m_Jumping;
  43.         private AudioSource m_AudioSource;
  44.  
  45.                 private CharacterController chCont;
  46.                 private UnityStandardAssets.Characters.FirstPerson.FirstPersonController fpsC;
  47.  
  48.                 chCont = GetComponent<CharacterController>();
  49.                 fpsC = gameObject.GetComponent<UnityStandardAssets.Characters.FirstPerson.FirstPersonController> ();
  50.  
  51.  
  52.  
  53.         // Use this for initialization
  54.         private void Start()
  55.         {
  56.             m_CharacterController = GetComponent<CharacterController>();
  57.             m_Camera = Camera.main;
  58.             m_OriginalCameraPosition = m_Camera.transform.localPosition;
  59.             m_FovKick.Setup(m_Camera);
  60.             m_HeadBob.Setup(m_Camera, m_StepInterval);
  61.             m_StepCycle = 0f;
  62.             m_NextStep = m_StepCycle/2f;
  63.             m_Jumping = false;
  64.             m_AudioSource = GetComponent<AudioSource>();
  65.                         m_MouseLook.Init(transform , m_Camera.transform);
  66.         }
  67.                        
  68.                 private bool m_CanRun = true;
  69.  
  70.                 public bool CanRun
  71.                 {
  72.                         get { return m_CanRun; }
  73.                         set { m_CanRun = value; }
  74.                 }
  75.  
  76.                 void FixedUpdate ()
  77.                 {      
  78.                         if(chCont.isGrounded && Input.GetKey(KeyCode.LeftShift)) {
  79.                                  Vector3 lastPosition;
  80.                                 currentStamina -= 1;
  81.                                 currentStamina = Mathf.Clamp(currentStamina, 0, maxStamina);
  82.                         }      
  83.  
  84.                         if (currentStamina > 0) {
  85.                                 fpsC.CanRun = true;
  86.                         } else {
  87.                                 fpsC.CanRun = false;
  88.                         }
  89.                 }
  90.  
  91.                 void Awake()
  92.                 {
  93.                         barHeight = Screen.height * 0.02f;
  94.                         barWidth = barHeight * 10.0f;
  95.  
  96.                         chCont = GetComponent<CharacterController>();
  97.                         fpsC = gameObject.GetComponent<UnityStandardAssets.Characters.FirstPerson.FirstPersonController> ();
  98.  
  99.                         lastPosition = transform.position;
  100.                 }
  101.  
  102.         // Update is called once per frame
  103.         private void Update()
  104.         {
  105.             RotateView();
  106.             // the jump state needs to read here to make sure it is not missed
  107.             if (!m_Jump)
  108.             {
  109.                 m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
  110.             }
  111.  
  112.             if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
  113.             {
  114.                 StartCoroutine(m_JumpBob.DoBobCycle());
  115.                 PlayLandingSound();
  116.                 m_MoveDir.y = 0f;
  117.                 m_Jumping = false;
  118.             }
  119.             if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
  120.             {
  121.                 m_MoveDir.y = 0f;
  122.             }
  123.  
  124.             m_PreviouslyGrounded = m_CharacterController.isGrounded;
  125.         }
  126.  
  127.  
  128.         private void PlayLandingSound()
  129.         {
  130.             m_AudioSource.clip = m_LandSound;
  131.             m_AudioSource.Play();
  132.             m_NextStep = m_StepCycle + .5f;
  133.         }
  134.  
  135.  
  136.         private void FixedUpdate()
  137.         {
  138.             float speed;
  139.             GetInput(out speed);
  140.             // always move along the camera forward as it is the direction that it being aimed at
  141.             Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
  142.  
  143.             // get a normal for the surface that is being touched to move along it
  144.             RaycastHit hitInfo;
  145.             Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
  146.                                m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
  147.             desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
  148.  
  149.             m_MoveDir.x = desiredMove.x*speed;
  150.             m_MoveDir.z = desiredMove.z*speed;
  151.  
  152.  
  153.             if (m_CharacterController.isGrounded)
  154.             {
  155.                 m_MoveDir.y = -m_StickToGroundForce;
  156.  
  157.                 if (m_Jump)
  158.                 {
  159.                     m_MoveDir.y = m_JumpSpeed;
  160.                     PlayJumpSound();
  161.                     m_Jump = false;
  162.                     m_Jumping = true;
  163.                 }
  164.             }
  165.             else
  166.             {
  167.                 m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
  168.             }
  169.             m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
  170.  
  171.             ProgressStepCycle(speed);
  172.             UpdateCameraPosition(speed);
  173.  
  174.             m_MouseLook.UpdateCursorLock();
  175.         }
  176.  
  177.  
  178.         private void PlayJumpSound()
  179.         {
  180.             m_AudioSource.clip = m_JumpSound;
  181.             m_AudioSource.Play();
  182.         }
  183.  
  184.  
  185.         private void ProgressStepCycle(float speed)
  186.         {
  187.             if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
  188.             {
  189.                 m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
  190.                              Time.fixedDeltaTime;
  191.             }
  192.  
  193.             if (!(m_StepCycle > m_NextStep))
  194.             {
  195.                 return;
  196.             }
  197.  
  198.             m_NextStep = m_StepCycle + m_StepInterval;
  199.  
  200.             PlayFootStepAudio();
  201.         }
  202.  
  203.  
  204.         private void PlayFootStepAudio()
  205.         {
  206.             if (!m_CharacterController.isGrounded)
  207.             {
  208.                 return;
  209.             }
  210.             // pick & play a random footstep sound from the array,
  211.             // excluding sound at index 0
  212.             int n = Random.Range(1, m_FootstepSounds.Length);
  213.             m_AudioSource.clip = m_FootstepSounds[n];
  214.             m_AudioSource.PlayOneShot(m_AudioSource.clip);
  215.             // move picked sound to index 0 so it's not picked next time
  216.             m_FootstepSounds[n] = m_FootstepSounds[0];
  217.             m_FootstepSounds[0] = m_AudioSource.clip;
  218.         }
  219.  
  220.  
  221.         private void UpdateCameraPosition(float speed)
  222.         {
  223.             Vector3 newCameraPosition;
  224.             if (!m_UseHeadBob)
  225.             {
  226.                 return;
  227.             }
  228.             if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
  229.             {
  230.                 m_Camera.transform.localPosition =
  231.                     m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
  232.                                       (speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
  233.                 newCameraPosition = m_Camera.transform.localPosition;
  234.                 newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
  235.             }
  236.             else
  237.             {
  238.                 newCameraPosition = m_Camera.transform.localPosition;
  239.                 newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
  240.             }
  241.             m_Camera.transform.localPosition = newCameraPosition;
  242.         }
  243.  
  244.  
  245.         private void GetInput(out float speed)
  246.         {
  247.             // Read input
  248.             float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
  249.             float vertical = CrossPlatformInputManager.GetAxis("Vertical");
  250.  
  251.             bool waswalking = m_IsWalking;
  252.  
  253. #if !MOBILE_INPUT
  254.             // On standalone builds, walk/run speed is modified by a key press.
  255.             // keep track of whether or not the character is walking or running
  256.             m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
  257. #endif
  258.             // set the desired speed to be walking or running
  259.             speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
  260.             m_Input = new Vector2(horizontal, vertical);
  261.  
  262.             // normalize input if it exceeds 1 in combined length:
  263.             if (m_Input.sqrMagnitude > 1)
  264.             {
  265.                 m_Input.Normalize();
  266.             }
  267.  
  268.             // handle speed change to give an fov kick
  269.             // only if the player is going to a run, is running and the fovkick is to be used
  270.             if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
  271.             {
  272.                 StopAllCoroutines();
  273.                 StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
  274.             }
  275.         }
  276.  
  277.  
  278.         private void RotateView()
  279.         {
  280.             m_MouseLook.LookRotation (transform, m_Camera.transform);
  281.         }
  282.  
  283.  
  284.         private void OnControllerColliderHit(ControllerColliderHit hit)
  285.         {
  286.             Rigidbody body = hit.collider.attachedRigidbody;
  287.             //dont move the rigidbody if the character is on top of it
  288.             if (m_CollisionFlags == CollisionFlags.Below)
  289.             {
  290.                 return;
  291.             }
  292.  
  293.             if (body == null || body.isKinematic)
  294.             {
  295.                 return;
  296.             }
  297.             body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
  298.         }
  299.     }
  300. }
  301.