Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Disable running and jumping?

Discussion in 'Scripting' started by Treasureman, May 19, 2016.

Thread Status:
Not open for further replies.
  1. Treasureman

    Treasureman

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

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Checking for a specific coordinate for a specific task isn't the best way to do because of floating point numbers. But i would suggest disabling its component(FPS controller) which is pretty simple. But you would want to decleare it first and acces it in Start function for performance reasons because accesing it every time you want to disable it is horrible.

    Code (csharp):
    1.  
    2. //using imports namespace neccesarry for your fps controller functions
    3. using UnityStandardAssets.Characters.FirstPerson;
    4.  
    5. //When you want to disable its movement use this
    6. FPSController.GetComponent<FirstPersonController>().enabled = false;
     
  3. Treasureman

    Treasureman

    Joined:
    Jul 5, 2014
    Posts:
    563
    No, that wouldn't work because I still want the player to walk. Just not run or jump
     
  4. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Be more specific next time,

    I see youre not allowing player to jump when it is grounded so make the same statement with your condition.
    For running idk, i never use FPS controller probably would just change speed to be lower.
     
  5. FireBjorne

    FireBjorne

    Joined:
    Jan 27, 2017
    Posts:
    1
    IDK if Treasureman has found a solution yet, but here's a neat little one I devised to disable the sprinting at least.
    Start by adding a new public Boolean at line 15:
    Code (csharp):
    1. public bool allowSprint;
    Then, replace line 223 with the following:
    Code (csharp):
    1.             if (!allowSprint)
    2.             {
    3.                 speed = m_WalkSpeed;
    4.             } else
    5.             {
    6.                 speed = m_IsWalking ? m_RunSpeed : m_WalkSpeed;
    7.             }
    Now you should have a checkbox to toggle sprint availability, and you can toggle allowSprint via any other script as well, such as the script that monitors the players position. Hope this helped!
     
    Last edited: Aug 10, 2017
  6. gamidev

    gamidev

    Joined:
    Feb 2, 2021
    Posts:
    1
    @Treasureman just make jumpspeed as 0 and put run speed same as walk speed
     
  7. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,374
    Please look at the dates of posts before you necro post. This is an old post from 2016!
     
Thread Status:
Not open for further replies.