Alright, so I recently needed to add a crouch function to the basic Unity First Person Controller for a project I'm working on. Not sure why it doesn't have one to begin with, but whatever. Here's how I went about it.
In the red box, we have a toggle function. When the player clicks the Left Control button, the script goes to an If block and checks the players height. Notice we are getting the players height, not scale. 2 is the players crouch height.
If the players height is equal to 2, the script registers that the player is not crouching and goes to the blue box. There, we set the players height to 0.9 with the first block, set their waling speed down to 2, and their sprint speed down to 3. It makes them short and slow, you now, like crouching does.
If the players height is not equal to 2, the script takes us to the yellow box, sets the player back to their normal height, which is 2, pulls the players walk speed back to 5 (but in this screenshot it pulls the speed from a variable because I want the player to be able to upgrade their move speed) and sets their sprint speed back to 8. All pretty simple.
I've made a version of this script before and done it in some worse ways that we can go over. I originally had a boolean Object Variable that could check if the player was couched and toggle the boolean on and off at the end of each arm. This is a lot more work than we need to do since we can just check the players height to see if they're already couched.
I also originally had the script change the players scale on the Y axis, but this change in scale also changed the scale for any child objects of the player. So, it smashed everything in their hands. Changing their height doesn't come with that same unwanted side effects.
Anyway, thanks for reading. Hope this works out for you.
No comments:
Post a Comment