Advertisement
Guest User

FirstPersonController.cs

a guest
Dec 21st, 2017
991
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.81 KB | None | 0 0
  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] private float m_RunSpeed;
  16.         [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
  17.         [SerializeField] private float m_JumpSpeed;
  18.         [SerializeField] private float m_StickToGroundForce;
  19.         [SerializeField] public 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.         // Variable pour le grappin
  46.         public bool CanMove;
  47.  
  48.         // Use this for initialization
  49.         private void Start()
  50.         {
  51.             m_CharacterController = GetComponent<CharacterController>();
  52.             m_Camera = Camera.main;
  53.             m_OriginalCameraPosition = m_Camera.transform.localPosition;
  54.             m_FovKick.Setup(m_Camera);
  55.             m_HeadBob.Setup(m_Camera, m_StepInterval);
  56.             m_StepCycle = 0f;
  57.             m_NextStep = m_StepCycle/2f;
  58.             m_Jumping = false;
  59.             m_AudioSource = GetComponent<AudioSource>();
  60.             m_MouseLook.Init(transform , m_Camera.transform);
  61.         }
  62.  
  63.  
  64.         // Update is called once per frame
  65.         private void Update()
  66.         {
  67.             RotateView();
  68.  
  69.             // Condition grappin
  70.             if (CanMove)
  71.             {
  72.                 // the jump state needs to read here to make sure it is not missed
  73.                 if (!m_Jump)
  74.                 {
  75.                     m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
  76.                 }
  77.  
  78.                 if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
  79.                 {
  80.                     StartCoroutine(m_JumpBob.DoBobCycle());
  81.                     PlayLandingSound();
  82.                     m_MoveDir.y = 0f;
  83.                     m_Jumping = false;
  84.                 }
  85.                 if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
  86.                 {
  87.                     m_MoveDir.y = 0f;
  88.                 }
  89.            
  90.                 m_PreviouslyGrounded = m_CharacterController.isGrounded;
  91.             }
  92.         }
  93.  
  94.  
  95.         private void PlayLandingSound()
  96.         {
  97.             m_AudioSource.clip = m_LandSound;
  98.             m_AudioSource.Play();
  99.             m_NextStep = m_StepCycle + .5f;
  100.         }
  101.  
  102.  
  103.         private void FixedUpdate()
  104.         {
  105.             float speed;
  106.             GetInput(out speed);
  107.             // always move along the camera forward as it is the direction that it being aimed at
  108.             Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
  109.  
  110.             // get a normal for the surface that is being touched to move along it
  111.             RaycastHit hitInfo;
  112.             Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
  113.                                m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
  114.             desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
  115.  
  116.             m_MoveDir.x = desiredMove.x*speed;
  117.             m_MoveDir.z = desiredMove.z*speed;
  118.  
  119.  
  120.             if (m_CharacterController.isGrounded)
  121.             {
  122.                 m_MoveDir.y = -m_StickToGroundForce;
  123.  
  124.                 if (m_Jump)
  125.                 {
  126.                     m_MoveDir.y = m_JumpSpeed;
  127.                     PlayJumpSound();
  128.                     m_Jump = false;
  129.                     m_Jumping = true;
  130.                 }
  131.             }
  132.             else
  133.             {
  134.                 m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
  135.             }
  136.             m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
  137.  
  138.             ProgressStepCycle(speed);
  139.             UpdateCameraPosition(speed);
  140.  
  141.             m_MouseLook.UpdateCursorLock();
  142.         }
  143.  
  144.  
  145.         private void PlayJumpSound()
  146.         {
  147.             m_AudioSource.clip = m_JumpSound;
  148.             m_AudioSource.Play();
  149.         }
  150.  
  151.  
  152.         private void ProgressStepCycle(float speed)
  153.         {
  154.             if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
  155.             {
  156.                 m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
  157.                              Time.fixedDeltaTime;
  158.             }
  159.  
  160.             if (!(m_StepCycle > m_NextStep))
  161.             {
  162.                 return;
  163.             }
  164.  
  165.             m_NextStep = m_StepCycle + m_StepInterval;
  166.  
  167.             PlayFootStepAudio();
  168.         }
  169.  
  170.  
  171.         private void PlayFootStepAudio()
  172.         {
  173.             if (!m_CharacterController.isGrounded)
  174.             {
  175.                 return;
  176.             }
  177.             // pick & play a random footstep sound from the array,
  178.             // excluding sound at index 0
  179.             int n = Random.Range(1, m_FootstepSounds.Length);
  180.             m_AudioSource.clip = m_FootstepSounds[n];
  181.             m_AudioSource.PlayOneShot(m_AudioSource.clip);
  182.             // move picked sound to index 0 so it's not picked next time
  183.             m_FootstepSounds[n] = m_FootstepSounds[0];
  184.             m_FootstepSounds[0] = m_AudioSource.clip;
  185.         }
  186.  
  187.  
  188.         private void UpdateCameraPosition(float speed)
  189.         {
  190.             Vector3 newCameraPosition;
  191.             if (!m_UseHeadBob)
  192.             {
  193.                 return;
  194.             }
  195.             if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
  196.             {
  197.                 m_Camera.transform.localPosition =
  198.                     m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
  199.                                       (speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
  200.                 newCameraPosition = m_Camera.transform.localPosition;
  201.                 newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
  202.             }
  203.             else
  204.             {
  205.                 newCameraPosition = m_Camera.transform.localPosition;
  206.                 newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
  207.             }
  208.             m_Camera.transform.localPosition = newCameraPosition;
  209.         }
  210.  
  211.  
  212.         private void GetInput(out float speed)
  213.         {
  214.             // Read input
  215.             float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
  216.             float vertical = CrossPlatformInputManager.GetAxis("Vertical");
  217.  
  218.             bool waswalking = m_IsWalking;
  219.  
  220. #if !MOBILE_INPUT
  221.             // On standalone builds, walk/run speed is modified by a key press.
  222.             // keep track of whether or not the character is walking or running
  223.             m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
  224. #endif
  225.             // set the desired speed to be walking or running
  226.             speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
  227.             m_Input = new Vector2(horizontal, vertical);
  228.  
  229.             // normalize input if it exceeds 1 in combined length:
  230.             if (m_Input.sqrMagnitude > 1)
  231.             {
  232.                 m_Input.Normalize();
  233.             }
  234.  
  235.             // handle speed change to give an fov kick
  236.             // only if the player is going to a run, is running and the fovkick is to be used
  237.             if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
  238.             {
  239.                 StopAllCoroutines();
  240.                 StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
  241.             }
  242.         }
  243.  
  244.  
  245.         private void RotateView()
  246.         {
  247.             m_MouseLook.LookRotation (transform, m_Camera.transform);
  248.         }
  249.  
  250.  
  251.         private void OnControllerColliderHit(ControllerColliderHit hit)
  252.         {
  253.             Rigidbody body = hit.collider.attachedRigidbody;
  254.             //dont move the rigidbody if the character is on top of it
  255.             if (m_CollisionFlags == CollisionFlags.Below)
  256.             {
  257.                 return;
  258.             }
  259.  
  260.             if (body == null || body.isKinematic)
  261.             {
  262.                 return;
  263.             }
  264.             body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
  265.         }
  266.     }
  267. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement