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.

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!.

–

Hi Guys, I find it works well, but my weapons are also shrinking ! Maybe 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 March!Need more input lol)

–

My 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?

–

I added the C# version, added it to first player controller, but nothing happens when I get into game? Help!

–

Thanks a lot for the question Edyvargas and for the very good answer Aldonaletto. for me that im a real ape when we are talking about programming this was a success ! I even felt like a little "Adventuring" and tried to make a prone script so basicly i made the height 0.1 instead of 0.5 (crouch height) but i dont really see much difference between both, any suggestions?

–

2 Answers

2

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.

Hi friend, really nice job, works 100% smooth, THANK YOU.

–

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.

–

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

–

Ok, done, thanks to explain me how this works :).

–

@SisterKy, 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.

–

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;
	}
}

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

–

Brilliant! Saved me so much time, works perfectly.

–

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!

–

This was a great help, appreciated!

–

Is there a way to control the amount of distance you can go running and how long till you can run again?

–