Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question How do I program crouching into an fps controller

Discussion in 'Editor & General Support' started by panic_media, Aug 25, 2020.

  1. panic_media

    panic_media

    Joined:
    May 2, 2020
    Posts:
    9
    Hi, I was wondering how I would be able to add crouching to my games FPS controller. here's the script for it
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {  
    7.  
    8.     public CharacterController controller;
    9.     public float speed = 12f;
    10.     public float gravity = -9.81f;
    11.     public float jumpHeight = 3f;
    12.  
    13.  
    14.     public Transform groundCheck;
    15.     public float groundDistance = 0.4f;
    16.     public LayerMask groundMask;
    17.  
    18.     Vector3 velocity;
    19.     bool isGrounded;
    20.  
    21.     void Update()
    22.     {  
    23.  
    24.         isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
    25.      
    26.         if(isGrounded && velocity.y < 0)
    27.         {
    28.             velocity.y = -2f;
    29.         }
    30.         float x = Input.GetAxis("Horizontal");
    31.         float z = Input.GetAxis("Vertical");
    32.  
    33.         Vector3 move = transform.right * x + transform.forward * z;
    34.  
    35.  
    36.         controller.Move(move * speed * Time.deltaTime);
    37.  
    38.         if(Input.GetButtonDown("Jump") && isGrounded)
    39.         {
    40.             velocity.y = Mathf.Sqrt(jumpHeight * - 2f * gravity);
    41.         }
    42.  
    43.         velocity.y += gravity * Time.deltaTime;
    44.  
    45.         controller.Move(velocity * Time.deltaTime);
    46.  
    47.     }
    48. }