First Person Controller - Crouching (EP04) [Unity Tutorial]

Поділитися
Вставка
  • Опубліковано 1 жов 2024
  • Welcome to part 4 of this on-going first person controller series, int this episode we're going to be covering how to crouch and stand effectively while also amending our movement speed WHILE we're crouching and also taking into consideration any obstacles above us before we stand back up!
    Join me and learn your way through the Unity Game Engine, the C# language and the Visual Studio editor. Remember, if this video was useful then DROP A LIKE! 👍
    🤩 SPONSORED LINKS:
    www.gigatank30...
    / gigatank3000
    Check out HEXED PERSPECTIVE:
    Soundcloud: / hexmane
    Spotify: open.spotify.c...
    Instagram: www.instagram....
    Apple Music: / hexmane
    💯 Want to help me out and allow me to keep making these tutorials? Consider supporting the channel on Patreon:
    / comp3interactive
    😍 AWESOME high quality 3D game assets available here:
    shop.runemarks...
    💬 Join the Discord community here:
    / discord
    📱 Find us on social media for more Tips and Tricks:
    / comp3interactive
    / comp3interactive
    / comp3int
    📱 Play our games for FREE here on Google Play:
    bit.ly/2TisAQo
    #UnityTutorial #Unity3D #Comp3interactive #GameDev

КОМЕНТАРІ • 171

  • @tommanninen5971
    @tommanninen5971 Рік тому +19

    Nice tutorial! I have a slight improvement however, since most people don't like just toggle crouch. You can make the method work for both sides of the argument by doing these changes:
    For the lambda, change the first conditional to:
    ShouldCrouch => (Input.GetKeyDown(crouchKey)||Input.GetKeyUp(crouchKey)) &&...
    Then move the isCrouching = !isCrouching; line just before the while statement. With this the input works like toggle crouch by simply tapping the key, but also obeys hold controls since it reads both down and up. The only downside is that it doesn't remember to get up from crouched position if the hold user lets go during a crawl segment, but that's like 2 additional lines of code of having it sit in a while loop.

    • @godin1179
      @godin1179 17 днів тому

      whats those 2 additional lines

  • @EpitomeTTV
    @EpitomeTTV 3 роки тому +43

    I absolutely love how organized you are when you're coding.

  • @MicahandModesta
    @MicahandModesta 3 роки тому +19

    1:20 - the answer is YES. I've been wanting a tutorial like this for SO long. Slick, user friendly and good flow of logic.

  • @OceanSlim
    @OceanSlim 3 роки тому +4

    Request to auto-uncrouch when pressing sprint key

  • @lgsgoosebumps7678
    @lgsgoosebumps7678 7 місяців тому +1

    if anyone wants to make their character uncrouch automatically if jump key is pressed, this modification could do it
    if (shouldJump)
    {
    if (isCrouching)
    StartCoroutine(crouchStand()); // Uncrouch if crouching
    moveDirection.y = jumpForce;
    }

  • @Crazylaika
    @Crazylaika Рік тому +2

    For anyone trying to make the player rise back up if the crouch key is not held down, I edited HandleCrouching()
    private void HandleCrouching() {
    if (shouldCrouch || isCrouching && !duringCrouchAnimation && !Input.GetKey(crouchKey)) {
    StartCoroutine(CrouchStand());
    }
    }

  • @hi-id2kn
    @hi-id2kn 3 роки тому +4

    If don't want to jump and run while crouching.
    private IEnumator CrouchStand()
    {
    ...
    isCrouching = !isCrouching;
    duringCrouchAnimation =false;
    canJump = !canJump;
    canSprint = !canSprint;
    }
    :)

  • @JimFKennedy
    @JimFKennedy 2 роки тому +3

    Is there any way to get this working with a hold function instead of toggle?

  • @Rise2034
    @Rise2034 3 роки тому +6

    omg I was searching for a tutorial for (crouch fps controller) and the notif pop! 😂 lol thanks! great job with all the amazing tutorial!

    • @comp3interactive
      @comp3interactive  3 роки тому +1

      That's happened a few times... I must just know 👀 😂

  • @ThrillerHeartStudios
    @ThrillerHeartStudios Рік тому +2

    Sadly when ever I get up from the crouch state my character jitters when getting up, is anybody else having a similar issue? It looks like when the player is getting up their collision is getting stuck in the ground then it corrects itself by popping the player up giving this jittering effect.

    • @JosephChancey
      @JosephChancey 9 місяців тому

      Have you been able to fix this? I am having the same issue

    • @JosephChancey
      @JosephChancey 9 місяців тому +1

      Update: after a few min of googling I found the fix. On the "Character Controller" component for the player, change the "Skin Width" parameter to "0.0001" No more jitter! :)

  • @nomadicjester
    @nomadicjester Рік тому +2

    Love the video but is there a way to change crouching to holding down the crouch key and when released you stand again? I want to implement sliding and this is giving me an issue. Any help would be appreciated.

  • @riskiereel4766
    @riskiereel4766 Рік тому +3

    nice tutorial, I only have 1 problem, I wanna make players hold the crouch button, not toggle crouching with the button.

  • @bastelbudi
    @bastelbudi 2 роки тому +2

    are you able to explain if i have third person model attached to the fps controller prefab as a child it will move up and down aswell. i need to avoid that but i cant find a solution. the model is moving with the capsule collider 😞

  • @eternalschism362
    @eternalschism362 Рік тому +3

    This format for your tutorials is quite good and completely clear. I appreciate you taking time from your work and life to make these.. Kudos man..
    Everything I have seen thus far has been very organized and with purpose and explanation. As a budding dev I have learned quite a bit. Thank you.

  • @onursimsek7234
    @onursimsek7234 Рік тому +1

    If we try to stand up without moving while our character is crouched, he works by tripping. please help i can't figure it out

  • @paulberry3359
    @paulberry3359 3 роки тому +5

    I have blasted through this tutorial series so far, and yes Mike I really enjoy the format you are using. It is so refreshing not to see public being thrown around everywhere. I have just completed a C# course for work and again nice to see the way that a Pro thinks about and lays out the code. As well as now going straight on to your Space Invaders. I want to research how to use the new input system and add and see if I can play around and get a basic shooter going. Thanks again! Awesome stuff

  • @2ksnakenoodles
    @2ksnakenoodles 3 роки тому +5

    Thank you for being a person who shows good code ethics, like properly labelling stuff with serializefield, etc.
    Love this series!

  • @mikkelduch2920
    @mikkelduch2920 2 роки тому +2

    If anyone like me wanted to add crouch while in air, follow these simple steps:
    1) Change "private bool ShouldCrouch => Input.GetKeyDown(crouchKey) && !duringCrouchAnimation && characterController.isGrounded;"
    To "private bool ShouldCrouch => Input.GetKeyDown(crouchKey) && !duringCrouchAnimation;"
    2) Change "currentInput = new Vector2((isCrouching ? crouchSpeed : IsSprinting ? sprintSpeed : walkSpeed) * Input.GetAxis("Vertical"), (isCrouching ? crouchSpeed : IsSprinting ? sprintSpeed : walkSpeed) * Input.GetAxis("Horizontal"));"
    To "Change "currentInput = new Vector2((isCrouching && characterController.isGrounded ? crouchSpeed : IsSprinting ? sprintSpeed : walkSpeed) * Input.GetAxis("Vertical"), (isCrouching && characterController.isGrounded ? crouchSpeed : IsSprinting ? sprintSpeed : walkSpeed) * Input.GetAxis("Horizontal"));"

  • @MaxxWrld
    @MaxxWrld 6 місяців тому

    I know this is a very late comment, but I'm having trouble with the camera and I hope someone can lend assistance.
    Whenever I crouch, the character controller's center and height does change, however, the position of the camera does not change whatsoever. How can I fix this?

  • @araskarimi8774
    @araskarimi8774 8 місяців тому

    i have an error please help
    Assets\scripts\FPS character scripts\FPSController.cs(113,10): error CS0246: The type or namespace name 'IEnumerator' could not be found (are you missing a using directive or an assembly reference?)

  • @creativerevolutions1173
    @creativerevolutions1173 2 роки тому +2

    I need help, I followed the tutorial and when I pressed the crouch button I can't stand back up pls help.

  • @Wolfie5309
    @Wolfie5309 3 роки тому +3

    Yes, I very much love your coding style. It's very similar to my own, I just have spent so much time out of the game (pun intended) that I have to relearn everything all over again

  • @Whateverpenguin
    @Whateverpenguin 8 місяців тому

    Very good, The only thing I'd really like to fix is like when crouching i'm able to jump, and it stays crouched, it could confuse my player to think this is just a really slow walk or something, can we like jump out of crouching back into standing please?

  • @reneklassen
    @reneklassen 3 роки тому +2

    I was looking for crouching tutorials because i couldnt figure it out on myself. I found your video and decided to restart the whole FPS Controller since yours is of such high quality :D These videos are great !!!
    Edit : i watched the full video... no wonder i couldnt figure out crouching on my own :,D this was hard but so fun

  • @JoseyThomasty
    @JoseyThomasty Рік тому

    can you please make a video on an inventory system like resident evil 8 or like My Friendly Neighborhood?

  • @Kiwi_Inventor
    @Kiwi_Inventor 7 місяців тому

    Can you please provide a link to your finished code? It speeds up the process quite a bit.

  • @moussagnaoui5427
    @moussagnaoui5427 2 роки тому +2

    Hey man, awsome tutorial, but i have a problem where if I uncrouch it doesnt return me to normal speed. How can I fix this?

  • @lilcabbage6326
    @lilcabbage6326 2 роки тому +1

    I tried to do this for a 3rd person character controller and it all works, except whenever i crouch the "leg" just seem to go through the floor. Now i know this is 1st person, however is there any way to "shrink" the character instead of just lowering it down? :)

  • @yellow2188
    @yellow2188 2 роки тому +1

    A lot of people ask how to do Auto-UnCrouch ))))

  • @ReemusXcII
    @ReemusXcII Рік тому

    when i press tab now i walk? and my crouch speed is still fast?

  • @LM-cc7qz
    @LM-cc7qz 2 роки тому +1

    PLEASE LIKE THIS SO MORE PEOPLE SEE IT, For those who have an issue where when pressing crouch your character crouches, but upon pressing crouch again the character stays in the crouch animation. What my issue was is that in the inspector for some reason my crouching and standing variables were Identical while in the code they were correct, I never edited them but for some reason they didn't match up with the code. I spent 2 whole hours rewriting this script just to find this out.

  • @bisugo3732
    @bisugo3732 2 роки тому +1

    how can i fix my crouch my speed when crouching sideways is the same of may walk speed and i can sprint sideways too

  • @liamwynn3269
    @liamwynn3269 2 роки тому +1

    Great tutorial, I just added it to my little project. One slight issue: you can break the code that prevents users from standing up if they are under something. You do so by 1) crouch 2) start standing up. 3) as you are standing up, move under a surface. I will experiment with this, but I think you need to add a constant ray cast check that will pause or terminate the while loop in CrouchStand if you detect a surface.

  • @raxacoricofallapatorius8484
    @raxacoricofallapatorius8484 2 роки тому +4

    I greatly appreciate your work. I am learning my way through.
    One thing I want to point out, crouchHeight of .5f is less than 18 inches!! There isn't an adult human that can crouch THAT low. This is an error many make. Here is a better chart:
    StandingHeight = 6ft
    CrouchHeight = 4ft
    KneelHeight=3ft
    CrawlHeight=2ft
    ProneHeight=1ft
    Yes it is in feet, but that was the rule-of-thumb measurements we used in the old days of game development (early 90s).
    Please keep up the fantastic work you are doing. Your presentation is top shelf!!

  • @switchback_sb
    @switchback_sb 11 місяців тому

    Why are you using a Raycast to check for a collider above the player? That is awful practice. Your controller is a capsule shape and the Raycast is a line so the sides of the capsule will still clip into the ceiling above.

    • @comp3interactive
      @comp3interactive  11 місяців тому +2

      Better question: Why are you watching beginner level tutorials if you already have method that works for you?

  • @Btomaek
    @Btomaek 11 місяців тому

    i didn't know about the center thing

  • @12Acorns
    @12Acorns 3 роки тому +1

    Could you for one of (or a future series) the tutorials be stamina.

  • @MicahandModesta
    @MicahandModesta 3 роки тому +1

    I ended up getting my first 'C' to work on the capsule and the camera. If I then click 'C' again, my capsule goes back to height 3, while my camera moves inversely down (sort of below floor level). I notice at this point, that my 'transform' position Y goes negative, even though my character controller goes Y = 3 (when standing) as expected. If I hit 'C' again, they will both return to the same correct 'crouched' position. I notice the large circle (blue) also goes beneath the floor with the camera, so I imagine it's that! Any recommendations?

    • @sborropoly
      @sborropoly 2 роки тому

      have u found the solution?

    • @ronahattingh4014
      @ronahattingh4014 2 роки тому

      My camera also went below the ground after coming out from crouching. I saw I did the following wrong:
      In my "Crouch Parameters " I wrote - [SerializeField] private Vector3 standingCentre = new Vector3(0, 0.0f, 0); after I fixed it to [SerializeField] private Vector3 standingCentre = new Vector3(0, 0, 0); my problem disappeared.
      Hope it helps.

  • @washynator
    @washynator 3 роки тому +1

    This is great! If only we could have more than once a week :(

  • @YTOrmy
    @YTOrmy Рік тому

    How do I stop the character from being able to jump whilst in the crouching state?

  • @trentthomas2771
    @trentthomas2771 2 роки тому +2

    is there any way to make this a hold to crouch instead of a toggle crouch?

    • @SamuelArmer
      @SamuelArmer 2 роки тому

      found a way?

    • @noisyproductions
      @noisyproductions 2 роки тому

      Change it from GetKeyDown to GetKey

    • @FONORX
      @FONORX 2 роки тому +1

      @@noisyproductions Does not work.

    • @heyimandrewbofo
      @heyimandrewbofo 2 роки тому +1

      @@noisyproductions Didn't work and I don't knowwhy

    • @voodookittoys7606
      @voodookittoys7606 2 роки тому +1

      Its a little buggy but maybe it helps
      using UnityEngine;
      using System.Collections;
      public class FirstPersonController : MonoBehaviour
      {
      public bool CanMove { get; private set; } = true;
      private bool isSprinting => canSprint && Input.GetKey(sprintKey);
      private bool ShouldJump => Input.GetKeyDown(jumpKey) && characterController.isGrounded;
      //private bool ShouldCrouch => Input.GetKeyDown(crouchKey) && !duringCrouchAnimation && characterController.isGrounded;
      [Header("Funktional Options")]
      [SerializeField] private bool canSprint = true;
      [SerializeField] private bool canJump = true;
      [SerializeField] private bool canCrouch = true;
      [SerializeField] private bool canUseHeadbob = true;
      [SerializeField] private bool WillSlideOnSlopes = true;
      [SerializeField] private bool canZoom = true;
      [Header("Controlls")]
      [SerializeField] private KeyCode sprintKey = KeyCode.LeftShift;
      [SerializeField] private KeyCode jumpKey = KeyCode.Space;
      [SerializeField] private KeyCode crouchKey = KeyCode.LeftControl;
      [SerializeField] private KeyCode zoomKey = KeyCode.Mouse1;
      [Header("Movement Parameters")]
      [SerializeField] private float walkSpeed = 3.0f;
      [SerializeField] private float sprintSpeed = 6.0f;
      [SerializeField] private float crouchSpeed = 1.5f;
      [SerializeField] private float slopeSpeed = 8f;
      [Header("Look Parameters")]
      [SerializeField, Range(1, 10)] private float lookSpeedX = 2.0f;
      [SerializeField, Range(1, 10)] private float lookSpeedY = 2.0f;
      [SerializeField, Range(1, 180)] private float upperLookLimit = 80.0f;
      [SerializeField, Range(1, 180)] private float lowerLookLimit = 80.0f;
      [Header("Jumping Parameters")]
      [SerializeField] private float jumpForce = 8.0f;
      [SerializeField] private float gravity = 30.0f;
      [Header("Crouch Prameters")]
      [SerializeField] private float crouchHeight = 0.5f;
      [SerializeField] private float standingHeight = 2.0f;
      [SerializeField] private float timeToCrouch = 0.25f;
      [SerializeField] Vector3 crouchingCenter = new Vector3(0,0.5f,0);
      [SerializeField] Vector3 standingCenter = new Vector3(0,0,0);
      private bool isCrouching;
      private bool duringCrouchAnimation;
      private Coroutine crouching;
      [Header("Headbob Parameters")]
      [SerializeField] private float walkBobSpeed = 14f;
      [SerializeField] private float walkBobAmount = 0.05f;
      [SerializeField] private float sprintBobSpeed = 18f;
      [SerializeField] private float sprintBobAmount = 0.1f;
      [SerializeField] private float crouchBobSpeed = 8f;
      [SerializeField] private float crouchBobAmount = 0.025f;
      private float defaultYPos = 0;
      private float timer;
      [Header("Zoom Parameters")]
      [SerializeField] private float timeToZoom = 0.3f;
      [SerializeField] private float zoomFOV = 30f;
      private float defaultFOV;
      private Coroutine zoomRoutine;
      // SlIDING PARAMETERS
      private Vector3 hitPointNormal;
      private bool IsSliding
      {
      get
      {
      if(characterController.isGrounded && Physics.Raycast(transform.position, Vector3.down, out RaycastHit slopeHit, 2f))
      {
      hitPointNormal = slopeHit.normal;
      return Vector3.Angle(hitPointNormal, Vector3.up) > characterController.slopeLimit;
      }
      else
      {
      return false;
      }
      }
      }
      private Camera playerCamera;
      private CharacterController characterController;
      private Vector3 moveDirection;
      private Vector2 currentInput;
      private float rotationX = 0;

      void Awake()
      {
      playerCamera = GetComponentInChildren();
      characterController = GetComponent();
      defaultYPos = playerCamera.transform.localPosition.y;
      defaultFOV = playerCamera.fieldOfView;
      Cursor.lockState = CursorLockMode.Locked;
      Cursor.visible = false;
      }
      void Update()
      {
      if (CanMove)
      {
      HandleMovementInput();
      HandleMouseLook();

      if(canJump)
      HandleJump();

      if(canCrouch)
      HandleCrouch();

      if(canUseHeadbob)
      HandleHeadbob();
      if(canZoom)
      HandleZoom();
      ApplyFinaleMovements();
      }
      }
      private void HandleMovementInput()
      {
      currentInput = new Vector2((isCrouching ? crouchSpeed : isSprinting ? sprintSpeed : walkSpeed) * Input.GetAxis("Vertical"), (isCrouching ? crouchSpeed : isSprinting ? sprintSpeed : walkSpeed) * Input.GetAxis("Horizontal"));
      float moveDirectionY = moveDirection.y;
      moveDirection = (transform.TransformDirection(Vector3.forward) * currentInput.x) + (transform.TransformDirection(Vector3.right) * currentInput.y);
      moveDirection.y = moveDirectionY;
      }
      private void HandleMouseLook()
      {
      rotationX -= Input.GetAxis("Mouse Y") * lookSpeedY;
      rotationX = Mathf.Clamp(rotationX, -upperLookLimit, lowerLookLimit);
      playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
      transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeedX, 0);
      }

      private void HandleJump()
      {
      if(ShouldJump)
      moveDirection.y = jumpForce;
      }
      private void HandleCrouch()
      {
      if(Input.GetKeyDown(crouchKey))
      {
      if(crouching != null)
      {
      StopCoroutine(crouching);
      crouching = null;
      }
      crouching = StartCoroutine(CrouchStand(true));
      }
      if(Input.GetKeyUp(crouchKey))
      {
      if(crouching != null)
      {
      StopCoroutine(crouching);
      crouching = null;
      }
      crouching = StartCoroutine(CrouchStand(false));
      }
      //if(ShouldCrouch)
      //StartCoroutine(CrouchStand());
      }
      private void HandleHeadbob()
      {
      if(!characterController.isGrounded) return;
      if(Mathf.Abs(moveDirection.x) > 0.1f || Mathf.Abs(moveDirection.z) > 0.1f)
      {
      timer += Time.deltaTime * (isCrouching ? crouchBobSpeed : isSprinting ? sprintBobSpeed : walkBobSpeed);
      playerCamera.transform.localPosition = new Vector3(
      playerCamera.transform.localPosition.x,
      defaultYPos + Mathf.Sin(timer) * (isCrouching ? crouchBobAmount : isSprinting ? sprintBobAmount : walkBobAmount),
      playerCamera.transform.localPosition.z);
      }
      }
      private void HandleZoom ()
      {
      if(Input.GetKeyDown(zoomKey))
      {
      if(zoomRoutine != null)
      {
      StopCoroutine(zoomRoutine);
      zoomRoutine = null;
      }
      zoomRoutine = StartCoroutine(ToggleZoom(true));
      }
      if(Input.GetKeyUp(zoomKey))
      {
      if(zoomRoutine != null)
      {
      StopCoroutine(zoomRoutine);
      zoomRoutine = null;
      }
      zoomRoutine = StartCoroutine(ToggleZoom(false));
      }
      }
      private void ApplyFinaleMovements()
      {
      if(!characterController.isGrounded)
      moveDirection.y -= gravity * Time.deltaTime;
      if(WillSlideOnSlopes && IsSliding)
      moveDirection += new Vector3(hitPointNormal.x, -hitPointNormal.y, hitPointNormal.z) * slopeSpeed;
      characterController.Move(moveDirection * Time.deltaTime);
      }
      private IEnumerator CrouchStand(bool isEnter)
      {
      if(isCrouching && Physics.Raycast(playerCamera.transform.position, Vector3.up, 1f))
      yield break;
      duringCrouchAnimation = true;
      float timeElapsed = 0;
      float targetHeight = isCrouching ? standingHeight : crouchHeight;
      float currentHeight = characterController.height;
      Vector3 targetCenter = isCrouching ? standingCenter : crouchingCenter;
      Vector3 currentCenter = characterController.center;
      while(timeElapsed < timeToCrouch)
      {
      characterController.height = Mathf.Lerp(currentHeight, targetHeight, timeElapsed/timeToCrouch);
      characterController.center = Vector3.Lerp(currentCenter, targetCenter, timeElapsed/timeToCrouch);
      timeElapsed += Time.deltaTime;
      yield return null;
      }
      characterController.height = targetHeight;
      characterController.center = targetCenter;
      isCrouching = !isCrouching;
      duringCrouchAnimation = false;
      }
      private IEnumerator ToggleZoom(bool isEnter)
      {
      float targetFOV = isEnter ? zoomFOV : defaultFOV;
      float startingFOV = playerCamera.fieldOfView;
      float timeElapsed = 0;
      while(timeElapsed < timeToZoom)
      {
      playerCamera.fieldOfView = Mathf.Lerp(startingFOV, targetFOV, timeElapsed/timeToZoom);
      timeElapsed += Time.deltaTime;
      yield return null;
      }
      playerCamera.fieldOfView = targetFOV;
      zoomRoutine = null;
      }
      }

  • @SleepyMatt-zzz
    @SleepyMatt-zzz 11 місяців тому

    I've played around with a lot of different FPS tutorials, and I gotta say, this is some clean code. Nice job, and thanks for the vids.

  • @Pneuma3D
    @Pneuma3D Рік тому

    Which version of unity is this. Been following along step by step even checking spelling is exact. Everything works except sprinting and crouching. The cs says no issues found but unity finds like 2 and I can't try until it's fixed.

  • @QuietStudiosOfficial
    @QuietStudiosOfficial 2 роки тому

    can you not do Mathf.SmoothDamp for the crouching animation? you won't even have to use a coroutine.

  • @residentsicko
    @residentsicko 3 роки тому +1

    Great tutorial again mate. Very clear and easy to follow. Will you be addressing the finer details such as footstep sounds? Without trying to get ahead of your schedule or spoiling any surprises. There are not many FPS controller tutorials that include things like that. Well not that I can see anyway.

    • @comp3interactive
      @comp3interactive  3 роки тому +4

      I will for sure, the idea is to make this a rolling series where we can bolt on additional features and use the functional options to toggle them on and off, footstep sounds is definitely on the radar!

    • @residentsicko
      @residentsicko 3 роки тому +2

      @@comp3interactive Awesome mate. I look forward to it. There are a few tutorials on making an FPS controller but none so far have truly included everything. Thanks again and keep up the good work.

  • @skymeyzz8431
    @skymeyzz8431 2 роки тому +1

    This is absolutely what I was looking for ! dude this series is amazing I just have a question, can we use it in our game and put your name in the credits ?

    • @comp3interactive
      @comp3interactive  2 роки тому +4

      Credits aren't required but obviously always appreciated ♥

  • @cbully
    @cbully 2 роки тому +1

    We need more tutorials like this.

  • @genofelice6034
    @genofelice6034 Рік тому

    Great tutorial series. Everything worked great. Well almost everything. I did have an issue with the player trying to stand from crouch in an area what he couldn't stand. The code Physics.Raycast(playerCamera.transform.position, Vector3.up, 1f); didn't seem to work. I solved the issue by using CheckSphere at the players current position + the players standing height Y position. I'm not sure what I did wrong to cause your code not to work but all's well that ends well. Thanks again

  • @frostmusicofficial
    @frostmusicofficial 2 роки тому

    So when the player is walking/sprinting and hits the crouch button, it crouches, how can I make it so when the player is walking while crouched can hit the crouch button to stand back up without having to stop moving?

  • @arrcommdwr
    @arrcommdwr Рік тому

    Great Series I am actually adding a "Crawling Parameter" the same time I am adding this Crouching Parameter. Been following these for 2 days and working great. Thank you for being such a "precise" trainer.

  • @skaruts
    @skaruts 2 роки тому

    I'm having an issue with this: my player is 1.8 high, but can't fit under a 2 high doorway. Same when crouching, it can't fit under places that should be high enough for it. Looking at the collider while playing I can see it's not actually touching the ground, it's slightly in the air (~0.1 units). But it's weird that it still seems like it should fit under the doorway despite that, but it doesn't.

  • @wuschelkopf5583
    @wuschelkopf5583 Рік тому

    I really appreciate this tutorial! But my character falls through the floor when I want to stop crouching...even though I followed all the steps. Does anyone have a clue what I did wrong?

  • @Jiry_XD
    @Jiry_XD 3 роки тому

    Hey man, I'am desperate and I need a tutorial for adding a rigged character with animations with first person. Van you help me out please, would relaly appreciate it man 😁

  • @crz6835
    @crz6835 Рік тому

    for some reason my isCrouching starts true does someone know how to solve this?

  • @smashboiiiminecraft
    @smashboiiiminecraft Рік тому

    sir can you make video on how to animate with these codes only ?? cuz i can't get that

  • @radiocage
    @radiocage Рік тому

    I come to your videos to get ideas of how to do things, and I always leave with a functional script. Thank you!

  • @benmcgregor7543
    @benmcgregor7543 3 роки тому

    Im getting an error where the isCrouching and duringCrouchingAnimation both say that "the name does not exist in the current context" how do I fix this?

  • @voodoolew
    @voodoolew 9 місяців тому

    "Because we can't crouch in mid air"
    Gordon Freeman would like a word

    • @Lexiosity
      @Lexiosity 2 місяці тому

      And Chell, too!

  • @MaximKarabaev
    @MaximKarabaev Рік тому

    I have to remind you about State pattern

  • @SamNBCA
    @SamNBCA 3 роки тому +1

    How would you go about having an option for only crouching when button is held?

  • @treyhayden4261
    @treyhayden4261 3 роки тому

    didn't know you could group attributes inside of the same bracket with a comma, +1

  • @JoshuaSpeedcubing
    @JoshuaSpeedcubing 2 роки тому

    Cannot implicitly convert type 'UnityEngine.Vector3' to 'float'
    my code:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class PlayerMovement : MonoBehaviour
    {
    public CharacterController controller;
    public float speed = 12f;
    public float gravity = -9.81f;
    public float jumpForce = 3f;
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    Vector3 velocity;
    bool isGrounded;
    private float crouchHeight = 0.5f;
    private float standHeight = 2f;
    private float timeToCrouch = 0.25f;
    private Vector3 crouchCentre = new Vector3(0, 0.5f, 0);
    private Vector3 standingCentre = new Vector3(0, 0, 0);
    private KeyCode crouchKey = KeyCode.LeftControl;
    private bool canCrouch = true;
    private bool isCrouching;
    private bool duringCrouchAnimation;
    private bool ShouldCrouch => Input.GetKeyDown(crouchKey) && !duringCrouchAnimation && CharacterController.isGrounded;
    // Update is called once per frame
    void Update()
    {
    isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
    if (isGrounded && velocity.y < 0)
    {
    velocity.y = -2f;
    }
    if (canCrouch)
    {
    HandleCrouch();
    }
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    Vector3 move = transform.right * x + transform.forward * z;
    controller.Move(move * speed * Time.deltaTime);
    velocity.y += gravity * Time.deltaTime;
    controller.Move(velocity * Time.deltaTime);
    if(Input.GetButtonDown("Jump") && isGrounded)
    {
    velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
    }
    }
    private void HandleCrouch()
    {
    if (ShouldCrouch)
    {
    StartCoroutine(CrouchStand());
    }
    }
    private IEnumerator CrouchStand()
    {
    duringCrouchAnimation = true;
    float timeElapsed = 0;
    float targetHeight = isCrouching ? standHeight : crouchHeight;
    float currentHeight = controller.height;
    Vector3 targetCenter = isCrouching ? standingCentre : crouchCentre;
    Vector3 currentCenter = controller.center;
    while(timeElapsed < timeToCrouch)
    {
    controller.height = Mathf.Lerp(currentHeight, targetHeight, timeElapsed/timeToCrouch);
    controller.height = Vector3.Lerp(currentCenter, crouchCentre, timeElapsed/timeToCrouch);
    timeElapsed += Time.deltaTime;
    yield return null;
    }
    controller.height = targetHeight;
    controller.center = targetCenter;
    isCrouching = !isCrouching;
    duringCrouchAnimation = false;
    }
    }

    • @comp3interactive
      @comp3interactive  2 роки тому +1

      Yup... You're lerping controller.height twice instead of controller.center for the Vector3... Remember when you said you copied it letter for letter?

  • @shang_psycho7414
    @shang_psycho7414 2 роки тому

    Excellent tutorial! Where did you learn C#?

  • @jynxx8954
    @jynxx8954 Рік тому

    your so good dude, the tutorials are a little tricky because I came from brackeys and he uses a lot more basic stuff to get the job done and such but your way of doing it is so efficient, really good stuff man

  • @reginaarbizu6017
    @reginaarbizu6017 2 роки тому

    Let me be honest, I'm new coding and at first I though following your instructions would be very difficult, but here I'm on the episode 4, and could follow the previous tutorials. Thank you!

  • @MrReallefauve
    @MrReallefauve 3 роки тому

    Great job, I follow several Unity tutorial channels, few channels are so clear, perfect pedagogy ... Simply brilliant.

  • @stravvman
    @stravvman 2 роки тому

    You should also disable jumping while crouching

  • @zanebrown5590
    @zanebrown5590 Рік тому

    This is by far the best place to come for tutorials! I already had a crouch script in my game, but I was looking for a way to stop crouching when something was above the players head.
    I of course came here to look first and ended up updating my crouch method. Great job!

  • @mohammedfarouk1729
    @mohammedfarouk1729 2 роки тому

    I want to exit crouch mode when I sprint , how can I do that ?

  • @akmalazizov2848
    @akmalazizov2848 2 роки тому

    how can i change IEnumerator to system.collection i couldn't find how to change it, could someone please help

    • @voodookittoys7606
      @voodookittoys7606 2 роки тому

      You have to write using System.Collections; at the very top under using UnityEngine

  • @X_Daniel466
    @X_Daniel466 3 роки тому

    I have been searching for while for FP controller series! Thank you.

  • @arreo1a626
    @arreo1a626 2 роки тому

    i actually use the left shift key to crouch

  • @apexxcode2197
    @apexxcode2197 2 роки тому

    Great job!~ I like that you implemented the collision above the player when crouching! Thanks for an epic series so far...

  • @rockthestar100
    @rockthestar100 Рік тому

    Noticed that when crouched, and pressing the key to stand back up while moving towards an overhang object, the character sliding for the short period does not continue to check if there is something above it can make the player stuck in the ceiling. But I suppose just eliminating the sliding feature would solve this, or by adding a continues check for above objects till the crouching movement animation is over.

    • @AstralEdgeInteractive
      @AstralEdgeInteractive 3 місяці тому

      I just added a trigger box collider on the top of player and it gets activated whenever player crouches. If box collider gets triggered the player will not be able to get up. Simple.

  • @fumein5588
    @fumein5588 2 роки тому

    if i press ctrl too much character falls below the ground and starts falling down to eternity. Did anyone experienced this ?

    • @fumein5588
      @fumein5588 2 роки тому +1

      i fixed it i removed the rigidbody component on the Player and its fixed

  • @smashboiiiminecraft
    @smashboiiiminecraft Рік тому

    have few doubts 1) my character crouches slowly i changed time to crouch to 0.01 then too this is happening
    2) my character does not crouch at first if i press it alot time then it crouches
    3) my character when crouches after when i press ctrl again to uncrouch at first it uncrouch but again crouches automatically
    4) i want a system so that when player is holding then only character should crouch instead of toggle
    anyone can help ???

    • @utkarshkumar8593
      @utkarshkumar8593 10 місяців тому

      Check in the ApplyFinalMovements function you are not doing characterController.velocity.y < -1 if Yes then remove this conditional statement and it'll fix it. I was also stuck for hours on this figured it out and resolved it. Thanks me later

  • @mjmu
    @mjmu 2 роки тому

    Loving the series so far and have just implemented the headbobbing and sliding. It's really useful and is helping me, a complete beginner, know the ins and outs of how to code in such a clean and concise manner.
    I've been having an issue when crouched and walking off a platform, once the character has stepped off a platform (and only) while crouched, the y movement speed is incredibly slow, barely falling -0.1 per second.
    Even while floating down, the debug log will say I'm not grounded but it still takes a while for the character to fall while crouched.
    Has anyone come across this or found a fix?

    • @utkarshkumar8593
      @utkarshkumar8593 10 місяців тому

      check in the ApplyFinalMovements function you are not doing characterController.velocity.y < -1 if Yes then remove this conditional statement and it'll fix it. I was also stuck for hours on this figured it out and resolved it. Thanks me later

  • @Izmblueskydownizm
    @Izmblueskydownizm 2 роки тому

    Thank You so much for you entire series, They have been so helpful . They are also very easy to follow

  • @robozombii
    @robozombii Рік тому

    easy to follow! im pretty sure i got everything right, crouching works and all my variables are as they should, but almost always its unresponsive unless i give a few clicks or spam for it to register. what i really want is for it to immediately crouch and stand the first time i click the key, is there anyway to fix that? im thinking it could have something to do with the device im on, since im not using a bulky desktop for this, but idk

    • @jynxx8954
      @jynxx8954 Рік тому +1

      if your code is 1:1 to his, it could be a performance issue, did you try build your project and test out crouching then? it should have better performance than in game view

    • @robozombii
      @robozombii Рік тому +1

      @@jynxx8954 after building it, i did see an improvement! thank you for answering :)

  • @dale7986
    @dale7986 Рік тому

    thank you for these!

  • @486x
    @486x Рік тому

    what is this shouldcrouch BS? it dosent work!

  • @Bat_pann
    @Bat_pann 3 роки тому

    Just what I needed, Thank you.

  • @joshk7893
    @joshk7893 2 роки тому

    you're amazing dude

  • @tokeitawa
    @tokeitawa Рік тому

    How do I do get the choice on which namespace you want to use? 7:12

    • @okthen4533
      @okthen4533 5 місяців тому

      Had an issue with this aswell, this is how I fixed it:
      1) Locate the first line of code, this should be:
      using UnityEngine;
      2) Move this to line 2, then on line 1, add:
      using System.Collections;
      3) This should result in your first two lines being:
      using System.Collections;
      using UnityEngine;
      4) Save and let the code update, and have fun. I'm not 100% on this being the same but it works for me.

  • @mohammedfarouk1729
    @mohammedfarouk1729 2 роки тому

    I want click and hold to crouch, I tired everything to change it but your script is too complex for me to adjust . I tried GetKey instead of GetKeyDown and now when I hold the character keep going up and down continuously, I just want to crouch when I hold and stand when I release, Please help.

    • @sborropoly
      @sborropoly 2 роки тому +1

      lemme know if u find a way bud

    • @mohammedfarouk1729
      @mohammedfarouk1729 2 роки тому +1

      @@sborropoly I tried what he did on the Zoom Tutorial (GetKeyDown, GetKeyUp , private IEnumerator CrouchStaand(bool isEnter)) on Crouching. Its kind of works but with some bugs like if y r under an object and you released the crouch key it will flip the loop (when I hold I stand & when I release I crouch)

  • @IAmScarab
    @IAmScarab 3 роки тому

    Another excellent tutorial with clear examples and explanation of the process of crouching. This is all starting to look very professional in the code great to see how its actually done in a real world game scenario. Keep it up dude.

  • @robertreilly4128
    @robertreilly4128 2 роки тому

    when I hit crouch I automatically move forward... does anyone know how to fix that? It stops after not crouching..

    • @robertreilly4128
      @robertreilly4128 2 роки тому +1

      fixed, double check to make sure you have enough brackets as so currentInput = new Vector2((isCrouching ? crouchSpeed : IsSprinting ? sprintSpeed : runSpeed) * Input.GetAxis("Vertical"), (isCrouching ? crouchSpeed : IsSprinting ? sprintSpeed : runSpeed) * Input.GetAxis("Horizontal"));

    • @redfactionofficial
      @redfactionofficial 2 роки тому

      @@robertreilly4128 Thank you

  • @skymeyzz8431
    @skymeyzz8431 2 роки тому

    this is awsome

  • @Fajerkoks
    @Fajerkoks 3 роки тому

    Thats insane

  • @noisyproductions
    @noisyproductions 2 роки тому

    920

  • @mnoel858
    @mnoel858 3 роки тому +2

    Amazing tutorial as always. I realized that there was no jumping while crouching and under an object was not handle. I updated the should jumping lambda as followed. "private bool ShouldJump => characterController.isGrounded && Input.GetKeyDown(jumpKey) && !Physics.Raycast(playerCamera.transform.position, Vector3.up, 1f); " But don't know how to jump from crouch into standing :/. Any advice?

    • @mnoel858
      @mnoel858 3 роки тому +3

      Here is my current solution for jumping out of crouching.
      void HandleJump()
      {
      if (ShouldJump)
      {
      float modifyJumpForce = 0;
      if (isCrouching)
      {
      StartCoroutine(CrouchStand());
      modifyJumpForce = 2f;
      }
      moveDirection.y = jumpForce + modifyJumpForce;
      }
      }

    • @Rise2034
      @Rise2034 3 роки тому

      @@mnoel858 thanks men appreciate!

    • @pokemad1998
      @pokemad1998 3 роки тому

      @@mnoel858 thanks buddy

  • @todorstoikovABV
    @todorstoikovABV 3 роки тому

    Hi, man, nice explaned tutorial, but i have problen with the controller. When i press C, to crouch the player, it's crouching, but when i press again C, to standup, it's fall trough the floor. Any suggestions.

    • @todorstoikovABV
      @todorstoikovABV 3 роки тому +1

      Never mind, I fixed it.

    • @MicahandModesta
      @MicahandModesta 3 роки тому +1

      What was your solution to this? I've not been able to solve it! :(

    • @todorstoikovABV
      @todorstoikovABV 3 роки тому

      @@MicahandModesta I had a test script attached that I forgot to remove. I removed it and everything worked properly.

    • @sborropoly
      @sborropoly 2 роки тому

      @@MicahandModesta have you found a solution ?

  • @nutsandy7183
    @nutsandy7183 3 роки тому

    love the tuts man, your accent (Wigan) makes you so easy to understand! Thanks!

    • @comp3interactive
      @comp3interactive  3 роки тому +1

      Ooo we don't say the Y word round here 😂! I'm from Wigan

    • @nutsandy7183
      @nutsandy7183 3 роки тому

      @@comp3interactive Corrected :p sorry for that massive insult :p

    • @SamuelArmer
      @SamuelArmer 2 роки тому +1

      well now im intrigued as to what the Y word is

  • @sborropoly
    @sborropoly 2 роки тому

    when i crouch my player goes into the floor, how can i fix this? any suggestions?

    • @Hypn0ninjaGaming
      @Hypn0ninjaGaming 2 роки тому +1

      Did you manage to fix this, my player falls through the floor when i crouch :(

    • @sborropoly
      @sborropoly 2 роки тому

      @@Hypn0ninjaGaming yeah, basically its about where the camera is placed and things like that, you should just play with thinghs around the player in unity, Its not something about the code

    • @sborropoly
      @sborropoly 2 роки тому +1

      @@Hypn0ninjaGaming now i cant remember very well what was the issue because it was 3 weeks ago, but i remember that i spent a lot of time doing things on the code but then i looked up where the camera placed when i crouched and stuff like that and i saw that weird stuff were happening. the camera used to invert from the head to the feet when I crouched and then if i tried again it started going in the center of the player but never in the head

    • @Hypn0ninjaGaming
      @Hypn0ninjaGaming 2 роки тому +1

      @@sborropoly thank you , i didnt think to look at the camera position. ill have a play around :)

  • @BrunoHiltune
    @BrunoHiltune Рік тому +1

    Fantastic tutorial. One problem that seems to be an inherent issue with the Character Controller component is that when we lerp the height/centre it shrinks towards the middle of the controller, resulting in the player kind of "floating" for a few seconds before falling down. This is most obvious when the timeToCrouch parameter is set to something small like 0.1 - the player will crouch down at a slower speed and then crouch up really fast.
    One thing I've tried to fix this is adding a simple downwards force like "playerVelocity = -10f" inside of the while statement right before the yield return null. This does work, but results in a very ugly jitter when playing at lower framerates, even at something like 60fps, to the point where I find it a poor solution.
    Is there a chance that you've maybe found a solution for this, or can think of something more elegant than my duct-tape fix?

    • @utkarshkumar8593
      @utkarshkumar8593 10 місяців тому

      check in the ApplyFinalMovements function you are not doing characterController.velocity.y < -1 if Yes then remove this conditional statement and it'll fix it. I was also stuck for hours on this figured it out and resolved it. Thanks me later

  • @aa_inc
    @aa_inc 2 роки тому

    Best fps tutorial series ever! Has everything I need! Using this for the Brackey's Game Jam and definitely putting your name in the credits!

    • @comp3interactive
      @comp3interactive  2 роки тому

      Good luck with the Jam dude! I signed up but I don't think I'm gonna have enough time to put something decent forward

    • @aa_inc
      @aa_inc 2 роки тому

      @@comp3interactive thanks man (:

  • @RealFakePhD
    @RealFakePhD 2 роки тому

    dude just let me copy paste the code, i dont have time to type all this shit. otherwise good stuff

  • @Ihatepe50
    @Ihatepe50 Рік тому

    when I leave the the center of the controller at 0,0,0 the camera moves with the crouch however there is a brief moment that my character is not longer grounded and is in a short freefall, to prevent this i set the center to 0,1,0 and it solved the grounding issue but now the camera remains at the original height. do i just need to add the same variables but for the camera transform and lerp between them or do i create a camera manager script and find a way to do it from there?
    Edit: I figured out a way just did the same Lerp with the vector3 for camera Holder local position