Search Unity

First Person Character Controller source code (Unity5)

Discussion in 'Scripting' started by ahdros, Aug 3, 2015.

  1. ahdros

    ahdros

    Joined:
    Aug 3, 2015
    Posts:
    5
    Can someone post here source code of the first person character controller from unity 5 please? I don’t want to upgrade to unity 5.x just yet, but Assets Store wouldn’t allow me to download standard assets pack for my 4.x version.

    p.s. sorry for bad English – not my native language :|
     
    Last edited: Aug 3, 2015
  2. ahdros

    ahdros

    Joined:
    Aug 3, 2015
    Posts:
    5
  3. Gerald Tyler

    Gerald Tyler

    Joined:
    Jul 10, 2015
    Posts:
    80
    Since there were no "That's against the rules" replies, and that it is freely accessible within a freely downloaded program...here you go.

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

    ahdros

    Joined:
    Aug 3, 2015
    Posts:
    5
    Thank you so much! :D
     
  5. Mr_12obot

    Mr_12obot

    Joined:
    Oct 7, 2015
    Posts:
    5
    Is there any code that accounts for colliders? I would like to see how Unity detects collisions, and more importantly, how it prevents the character from walking into walls while also allowing the character to walk along walls.

    (only possibility I can think of is that it detects the normal of the collider at the point where the character contacts it, and then it removes all components of the movement along that normal.... is there code for this?)
     
  6. OUTBREAK_90

    OUTBREAK_90

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

    OUTBREAK_90

    Joined:
    Jan 22, 2020
    Posts:
    2
    this code if you entred unity talk this script is no found
    and my player no move
    plz help me guys