Search Unity

Unity 5 FPSController walking on its own for a second

Discussion in 'Scripting' started by Siliwinter, Feb 7, 2016.

  1. Siliwinter

    Siliwinter

    Joined:
    Dec 6, 2015
    Posts:
    15
    Hello i have this problem with unity unlike games i play with that are made with unity i am following Jimmy Vegas tutorial on making a game but with whatever project i make Unity's standerd FPSController walks on its own for like 0.5-1 seconds then stops,

    in any direction too, this is the script:

    Code (CSharp):
    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. publicclassFirstPersonController:MonoBehaviour
    12. {
    13. [SerializeField]privateboolm_IsWalking;
    14. [SerializeField]privatefloatm_WalkSpeed;
    15. [SerializeField]privatefloatm_RunSpeed;
    16. [SerializeField][Range(0f,1f)]privatefloatm_RunstepLenghten;
    17. [SerializeField]privatefloatm_JumpSpeed;
    18. [SerializeField]privatefloatm_StickToGroundForce;
    19. [SerializeField]privatefloatm_GravityMultiplier;
    20. [SerializeField]privateMouseLookm_MouseLook;
    21. [SerializeField]privateboolm_UseFovKick;
    22. [SerializeField]privateFOVKickm_FovKick=newFOVKick();
    23. [SerializeField]privateboolm_UseHeadBob;
    24. [SerializeField]privateCurveControlledBobm_HeadBob=newCurveControlledBob();
    25. [SerializeField]privateLerpControlledBobm_JumpBob=newLerpControlledBob();
    26. [SerializeField]privatefloatm_StepInterval;
    27. [SerializeField]privateAudioClip[]m_FootstepSounds;//anarrayoffootstepsoundsthatwillberandomlyselectedfrom.
    28. [SerializeField]privateAudioClipm_JumpSound;//thesoundplayedwhencharacterleavestheground.
    29. [SerializeField]privateAudioClipm_LandSound;//thesoundplayedwhencharactertouchesbackonground.
    30.  
    31. privateCameram_Camera;
    32. privateboolm_Jump;
    33. privatefloatm_YRotation;
    34. privateVector2m_Input;
    35. privateVector3m_MoveDir=Vector3.zero;
    36. privateCharacterControllerm_CharacterController;
    37. privateCollisionFlagsm_CollisionFlags;
    38. privateboolm_PreviouslyGrounded;
    39. privateVector3m_OriginalCameraPosition;
    40. privatefloatm_StepCycle;
    41. privatefloatm_NextStep;
    42. privateboolm_Jumping;
    43. privateAudioSourcem_AudioSource;
    44.  
    45. //Usethisfor initialization
    46. privatevoidStart()
    47. {
    48. m_CharacterController=GetComponent<CharacterController>();
    49. m_Camera=Camera.main;
    50. m_OriginalCameraPosition=m_Camera.transform.localPosition;
    51. m_FovKick.Setup(m_Camera);
    52. m_HeadBob.Setup(m_Camera,m_StepInterval);
    53. m_StepCycle=0f;
    54. m_NextStep=m_StepCycle/2f;
    55. m_Jumping=false;
    56. m_AudioSource=GetComponent<AudioSource>();
    57. m_MouseLook.Init(transform,m_Camera.transform);
    58. }
    59.  
    60.  
    61. //Updateiscalledonceper frame
    62. privatevoidUpdate()
    63. {
    64. RotateView();
    65. //thejumpstateneedstoreadheretomakesureitisnot missed
    66. if(!m_Jump)
    67. {
    68. m_Jump=CrossPlatformInputManager.GetButtonDown("Jump");
    69. }
    70.  
    71. if(!m_PreviouslyGrounded&&m_CharacterController.isGrounded)
    72. {
    73. StartCoroutine(m_JumpBob.DoBobCycle());
    74. PlayLandingSound();
    75. m_MoveDir.y=0f;
    76. m_Jumping=false;
    77. }
    78. if(!m_CharacterController.isGrounded&& !m_Jumping&&m_PreviouslyGrounded)
    79. {
    80. m_MoveDir.y=0f;
    81. }
    82.  
    83. m_PreviouslyGrounded=m_CharacterController.isGrounded;
    84. }
    85.  
    86.  
    87. privatevoidPlayLandingSound()
    88. {
    89. m_AudioSource.clip=m_LandSound;
    90. m_AudioSource.Play();
    91. m_NextStep=m_StepCycle+.5f;
    92. }
    93.  
    94.  
    95. privatevoidFixedUpdate()
    96. {
    97. floatspeed;
    98. GetInput(outspeed);
    99. //alwaysmovealongthecameraforwardasitisthedirectionthatitbeingaimed at
    100. Vector3desiredMove=transform.forward*m_Input.y+transform.right*m_Input.x;
    101.  
    102. //getanormalforthesurfacethatisbeingtouchedtomovealong it
    103. RaycastHithitInfo;
    104. Physics.SphereCast(transform.position,m_CharacterController.radius,Vector3.down,outhitInfo,
    105. m_CharacterController.height/2f, ~0,QueryTriggerInteraction.Ignore);
    106. desiredMove=Vector3.ProjectOnPlane(desiredMove,hitInfo.normal).normalized;
    107.  
    108. m_MoveDir.x=desiredMove.x*speed;
    109. m_MoveDir.z=desiredMove.z*speed;
    110.  
    111.  
    112. if(m_CharacterController.isGrounded)
    113. {
    114. m_MoveDir.y=-m_StickToGroundForce;
    115.  
    116. if(m_Jump)
    117. {
    118. m_MoveDir.y=m_JumpSpeed;
    119. PlayJumpSound();
    120. m_Jump=false;
    121. m_Jumping=true;
    122. }
    123. }
    124. else
    125. {
    126. m_MoveDir+=Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
    127. }
    128. m_CollisionFlags=m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
    129.  
    130. ProgressStepCycle(speed);
    131. UpdateCameraPosition(speed);
    132.  
    133. m_MouseLook.UpdateCursorLock();
    134. }
    135.  
    136.  
    137. privatevoidPlayJumpSound()
    138. {
    139. m_AudioSource.clip=m_JumpSound;
    140. m_AudioSource.Play();
    141. }
    142.  
    143.  
    144. privatevoidProgressStepCycle(floatspeed)
    145. {
    146. if(m_CharacterController.velocity.sqrMagnitude>0&&(m_Input.x !=0 || m_Input.y !=0))
    147. {
    148. m_StepCycle+=(m_CharacterController.velocity.magnitude+(speed*(m_IsWalking?1f:m_RunstepLenghten)))*
    149. Time.fixedDeltaTime;
    150. }
    151.  
    152. if(!(m_StepCycle>m_NextStep))
    153. {
    154. return;
    155. }
    156.  
    157. m_NextStep=m_StepCycle+m_StepInterval;
    158.  
    159. PlayFootStepAudio();
    160. }
    161.  
    162.  
    163. privatevoidPlayFootStepAudio()
    164. {
    165. if(!m_CharacterController.isGrounded)
    166. {
    167. return;
    168. }
    169. //pick&playarandomfootstepsoundfromthearray,
    170. //excludingsoundatindex 0
    171. intn=Random.Range(1,m_FootstepSounds.Length);
    172. m_AudioSource.clip=m_FootstepSounds[n];
    173. m_AudioSource.PlayOneShot(m_AudioSource.clip);
    174. //movepickedsoundtoindex0soit'snotpickednext time
    175. m_FootstepSounds[n]=m_FootstepSounds[0];
    176. m_FootstepSounds[0]=m_AudioSource.clip;
    177. }
    178.  
    179.  
    180. privatevoidUpdateCameraPosition(floatspeed)
    181. {
    182. Vector3newCameraPosition;
    183. if(!m_UseHeadBob)
    184. {
    185. return;
    186. }
    187. if(m_CharacterController.velocity.magnitude>0&&m_CharacterController.isGrounded)
    188. {
    189. m_Camera.transform.localPosition=
    190. m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude+
    191. (speed*(m_IsWalking?1f:m_RunstepLenghten)));
    192. newCameraPosition=m_Camera.transform.localPosition;
    193. newCameraPosition.y=m_Camera.transform.localPosition.y-m_JumpBob.Offset();
    194. }
    195. else
    196. {
    197. newCameraPosition=m_Camera.transform.localPosition;
    198. newCameraPosition.y=m_OriginalCameraPosition.y-m_JumpBob.Offset();
    199. }
    200. m_Camera.transform.localPosition=newCameraPosition;
    201. }
    202.  
    203.  
    204. privatevoidGetInput(outfloatspeed)
    205. {
    206. //Read input
    207. floathorizontal=CrossPlatformInputManager.GetAxis("Horizontal");
    208. floatvertical=CrossPlatformInputManager.GetAxis("Vertical");
    209.  
    210. boolwaswalking=m_IsWalking;
    211.  
    212. #if!MOBILE_INPUT
    213. //Onstandalonebuilds,walk/runspeedismodifiedbyakeypress.
    214. //keeptrackofwhetherornotthecharacteriswalkingor running
    215. m_IsWalking= !Input.GetKey(KeyCode.LeftShift);
    216. #endif
    217. //setthedesiredspeedtobewalkingor running
    218. speed=m_IsWalking?m_WalkSpeed:m_RunSpeed;
    219. m_Input=newVector2(horizontal,vertical);
    220.  
    221. //normalizeinputifitexceeds1incombinedlength:
    222. if(m_Input.sqrMagnitude>1)
    223. {
    224. m_Input.Normalize();
    225. }
    226.  
    227. //handlespeedchangetogiveanfov kick
    228. //onlyiftheplayerisgoingtoarun,isrunningandthefovkickistobe used
    229. if(m_IsWalking !=waswalking&&m_UseFovKick&&m_CharacterController.velocity.sqrMagnitude>0)
    230. {
    231. StopAllCoroutines();
    232. StartCoroutine(!m_IsWalking?m_FovKick.FOVKickUp():m_FovKick.FOVKickDown());
    233. }
    234. }
    235.  
    236.  
    237. privatevoidRotateView()
    238. {
    239. m_MouseLook.LookRotation(transform,m_Camera.transform);
    240. }
    241.  
    242.  
    243. privatevoidOnControllerColliderHit(ControllerColliderHithit)
    244. {
    245. Rigidbodybody=hit.collider.attachedRigidbody;
    246. //dontmovetherigidbodyifthecharacterisontopof it
    247. if(m_CollisionFlags==CollisionFlags.Below)
    248. {
    249. return;
    250. }
    251.  
    252. if(body==null || body.isKinematic)
    253. {
    254. return;
    255. }
    256. body.AddForceAtPosition(m_CharacterController.velocity*0.1f,hit.point,ForceMode.Impulse);
    257. }
    258. }
    259. }
     
    Last edited: Feb 9, 2016
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Put your scripts into code tags (under insert/code). It helps the visibility a lot
     
    Laperen likes this.
  3. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    In addition to the above good advice, in the GetInput() method try changing

    Code (CSharp):
    1.  
    2. floathorizontal=CrossPlatformInputManager.GetAxis("Horizontal");
    3. floatvertical=CrossPlatformInputManager.GetAxis("Vertical");
    to

    Code (CSharp):
    1.  
    2. floathorizontal=CrossPlatformInputManager.GetAxisRaw("Horizontal");
    3. floatvertical=CrossPlatformInputManager.GetAxisRaw("Vertical");
    because the version in your code has a 'speedup' and 'slowdown' factor built into the input. The GetAxisRaw version returns zero or 1 only.
     
  4. Siliwinter

    Siliwinter

    Joined:
    Dec 6, 2015
    Posts:
    15
    Thanks man you are the most helpful guy eva! now is there a way for me to make the stopping smoother perhaps
     
  5. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    You could script a deceleration behaviour when you detect 0 input on the axis, using GetAxisRaw(), or, possibly easier to do would be to revert to using GetAxis() and then modify the Axes settings for horizontal and vertical input in the InputManager (Edit->Project Settings->Input)

    I believe the sensitivity setting determines how fast it goes from zero to 1 when it detects input, and the gravity setting determines how quickly it slows back down to zero when there is no input detected. The default setting for both is 3.

    So for your case, if you want it to slow down faster than normal, but not instantly, you should try changing the gravity setting to something higher than 3, until you achieve the effect you want.