Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
6
Question by Edyvargas · Sep 08, 2011 at 01:13 AM · fpsfirst-person-controllerruncrouch

How to Make the FPS Character Controller RUN and CROUCH

Hi everybody, how can i tweak the FPS Character Controller to make my character can RUN and CROUCH?, Thank you.

Comment
Add comment · Show 8
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image viktor15328 · Dec 14, 2011 at 10:47 AM 0
Share

Thank you it helped alot. But i followed the istructions by edyvargas and it said i could not place i on the character beacouse the name did not match, so i had to change the name from RunAndCrouch.js to just RunAndCrouch.

But thanks anyway.

avatar image Edyvargas · Dec 14, 2011 at 02:29 PM 0
Share

Hi viktor15328, sorry for the misunderstood, the ".js" its automatic, it means the file format, in this case "javascript" (the first comment is already edited), the name then, would be only "RunAndCrouch", or any other name you preffer to use, the name of the script can be whatever you want, but try to give it a name that helps you work in your project. Good Luck!.

avatar image Chuckler · May 27, 2012 at 05:56 PM 0
Share

Hi Guys, I find it works well, but my weapons are also shrinking ! $$anonymous$$aybe if children object would not be affected somehow that would fix it. I havn't seemed to be able to get around it so far and i would like to get my FPS character to CROUCH and LEAN as well. Is anyone else getting that effect? (i started using unity in $$anonymous$$arch!Need more input lol)

avatar image jForsstrom · Jun 10, 2012 at 09:54 AM 0
Share

Works great! I just have 1 problem: when i release all buttons after sprinting the character starts sliding... any help?

avatar image Red Sentinel · Jan 07, 2013 at 01:10 AM 0
Share

$$anonymous$$y first person controller seems to sprint whenever I go sideways at the same speed as it is meant to be sprinting, even when I am not holding the sprint button. Can I have some help with this please?

Show more comments

2 Replies

· Add your reply
  • Sort: 
avatar image
34
Best Answer

Answer by aldonaletto · Sep 08, 2011 at 03:25 AM

The basic idea is simple: use different speeds when walking, running or crouching, and to crouch reduce the character vertical scale (remember to fix the character position while standing up to avoid falling through the floor). But if you are using the First Person Controller that comes with Unity, however, this may be a really hard job: it uses CharacterMotor.js, a very complicated script that usually drives crazy anyone who try to modify it. I know this very well: I was one of them... but I survived, and learned enough to do some tricks - including this!
To avoid editing the terrible CharacterMotor.js, I put all the code in this script; attach it to the First Person Controller, and they will communicate and do the magic:

 var walkSpeed: float = 7; // regular speed
 var crchSpeed: float = 3; // crouching speed
 var runSpeed: float = 20; // run speed
 
 private var chMotor: CharacterMotor;
 private var tr: Transform;
 private var dist: float; // distance to ground
 
 function Start(){
     chMotor = GetComponent(CharacterMotor);
     tr = transform;
     var ch:CharacterController = GetComponent(CharacterController);
     dist = ch.height/2; // calculate distance to ground
 }
 
 function Update(){
 
     var vScale = 1.0;
     var speed = walkSpeed;
     
     if (chMotor.grounded && Input.GetKey("left shift") || Input.GetKey("right shift")){
         speed = runSpeed;
     }
     if (Input.GetKey("c")){ // press C to crouch
         vScale = 0.5;
         speed = crchSpeed; // slow down when crouching
     }
     chMotor.movement.maxForwardSpeed = speed; // set max speed
     var ultScale = tr.localScale.y; // crouch/stand up smoothly 
     tr.localScale.y = Mathf.Lerp(tr.localScale.y, vScale, 5*Time.deltaTime);
     tr.position.y += dist * (tr.localScale.y-ultScale); // fix vertical position
 }

EDITED: @bacca87 posted a C# version below, and also included a fix to avoid run speed while in the air - feature that I've added to this answer.

EDITED 2: The script above works, but has the bad collateral effect of modifying the vertical scale of any character child - like the weapon, as @Fishman92 noticed! To avoid this, the version below modify the character height instead of its vertical scale:

 var walkSpeed: float = 7; // regular speed
 var crchSpeed: float = 3; // crouching speed
 var runSpeed: float = 20; // run speed
 
 private var chMotor: CharacterMotor;
 private var ch: CharacterController;
 private var tr: Transform;
 private var height: float; // initial height
 
 function Start(){
     chMotor = GetComponent(CharacterMotor);
     tr = transform;
     ch = GetComponent(CharacterController);
     height = ch.height;
 }
 
 function Update(){
 
     var h = height;
     var speed = walkSpeed;
     
     if (ch.isGrounded && Input.GetKey("left shift") || Input.GetKey("right shift")){
         speed = runSpeed;
     }
     if (Input.GetKey("c")){ // press C to crouch
         h = 0.5 * height;
         speed = crchSpeed; // slow down when crouching
     }
     chMotor.movement.maxForwardSpeed = speed; // set max speed
     var lastHeight = ch.height; // crouch/stand up smoothly 
     ch.height = Mathf.Lerp(ch.height, h, 5*Time.deltaTime);
     tr.position.y += (ch.height-lastHeight)/2; // fix vertical position
 }

NOTE: The white capsule childed to the FPC ("Graphics") isn't modified by this script, thus it will sink a little in the terrain when crouching. A similar problem will happen when the player crouches under a low ceiling: the top of the capsule will penetrate the ceiling. This makes no difference, since "Graphics" doesn't have a collider.

Comment
Add comment · Show 30 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Edyvargas · Sep 08, 2011 at 03:29 PM 1
Share

Hi friend, really nice job, works 100% smooth, THAN$$anonymous$$ YOU.

avatar image Edyvargas · Sep 08, 2011 at 03:43 PM 0
Share

To someone who wants to know how to do this exactly, follow this steps:

(First you must have the "First Person Controller" that came with Unity, placed on your Hierarchy, you can found it on the standard assets on Character Controller).

  • Create a new Javascript code on: Project, create, JavaScript, and call the code "RunAndCrouch" (or put the name you want).

  • Then attach the new code to your "First Person Controller" at the Hierarchy, and volia!

Works very good, thanks again to the creator for sharing this code.

avatar image SisterKy · Sep 08, 2011 at 06:46 PM 0
Share

please mark aldonalettos answer as the 'accepted' (little checkmark top-left of this post). This will give him his well-deserved karma points :)

avatar image aldonaletto · Sep 09, 2011 at 12:13 PM 2
Share

@Sister$$anonymous$$y, unfortunately we don't gain any karma when our answer is accepted anymore :(
Presently, only up votes can feed our karma. Somewhat unfair, but avoids stress when there are several acceptable answers. On the other hand, accepting more than one answer (like it was in the past) would be a better approach.

avatar image aldonaletto · Feb 19, 2013 at 11:38 AM 1
Share

Your doubt isn't stupid: if Update looped continuously, the work would be wasted. But that's not what actually happens - each loop iteration follows a sequence: Unity first calls all Update functions in all scripts, then renders the frame and transfers it to the screen. That's why most code in Unity goes in Update: any changes done in Update affect the frame that's going to be rendered next.
In this case, Update assumes initally the original height, and modify it according to the crouch key. When Update finishes, the character has the intended height, speed etc. Then, the frame is rendered according to the current character state.

Show more comments
avatar image
14

Answer by bacca87 · Apr 14, 2012 at 12:45 PM

This is the C# version of the script with a little fix that prevent the character to run while jumping.


 using UnityEngine;
 using System.Collections;
 
 public class RunAndCrouch : MonoBehaviour 
 {
     public float walkSpeed = 7; // regular speed
     public float crchSpeed = 3; // crouching speed
     public float runSpeed = 20; // run speed
     
     private CharacterMotor chMotor;
     private Transform tr;
     private float dist; // distance to ground
     
     // Use this for initialization
     void Start () 
     {
         chMotor =  GetComponent<CharacterMotor>();
         tr = transform;
         CharacterController ch = GetComponent<CharacterController>();
         dist = ch.height/2; // calculate distance to ground
     }
     
     // Update is called once per frame
     void FixedUpdate ()
     {
         float vScale = 1.0f;
         float speed = walkSpeed;
         
         if ((Input.GetKey("left shift") || Input.GetKey("right shift")) && chMotor.grounded)
         {
             speed = runSpeed;            
         }
         
         if (Input.GetKey("c"))
         { // press C to crouch
             vScale = 0.5f;
             speed = crchSpeed; // slow down when crouching
         }
         
         chMotor.movement.maxForwardSpeed = speed; // set max speed
         float ultScale = tr.localScale.y; // crouch/stand up smoothly 
         
         Vector3 tmpScale = tr.localScale;
         Vector3 tmpPosition = tr.position;
         
         tmpScale.y = Mathf.Lerp(tr.localScale.y, vScale, 5 * Time.deltaTime);
         tr.localScale = tmpScale;
         
         tmpPosition.y += dist * (tr.localScale.y - ultScale); // fix vertical position        
         tr.position = tmpPosition;
     }
 }
Comment
Add comment · Show 16 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image aldonaletto · Apr 24, 2012 at 11:16 AM 0
Share

Good point! Accelerating the character while in the air is really a stupid collateral effect. I'll include this fix in my answer. Thanks!

avatar image atlantis · Apr 25, 2012 at 07:50 AM 0
Share

HI brilliant C# script very use full for my little project...

But: Is it possible to make the vscale smaller then 0.5f..cause when i make 0.3 first person controller is falling trough floor ....

regards: Atlantis

avatar image Richard 3 · Jun 13, 2012 at 06:46 AM 0
Share

Brilliant! Saved me so much time, works perfectly.

avatar image yohan · Aug 13, 2012 at 05:38 PM 0
Share

Thank you very much for the Script! However, I have a problem where the character would fall through the Terrain or penetrate into a concave wall when I stand up, which I believe is the cause of the capsule collision (character controller) scaling from 50% to 100% its original size and thus penetrating through colliders.

Any help on the script to address this issue is greatly appreciated!

avatar image LeakySink · Oct 24, 2012 at 08:51 PM 0
Share

This was a great help, appreciated!

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

51 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Make character either crouch or go prone depending on how long a button is held? 0 Answers

Crosshair? How? 6 Answers

C# Crouch script problem 1 Answer

How do I add a sprint recharge 1 Answer

How do you say if("Capslock") is on? 4 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges