Dear community, I am fairly new for to coding in c# and I tried to get my character controller to be able to run and crouch.
I got him to crouch but not slow down, could anyone take a look at my code and help me solve this?
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(CharacterController))]
public class FirstPersonController : MonoBehaviour {
public float runSpeed = 20.0f;
public float crchSpeed = 3.0f;
public float movementSpeed = 5.0f;
public float mouseSensivity = 5.0f;
public float jumpSpeed = 7.0f;
private Transform tr;
private float dist; // distance to ground
float verticalRotation = 0;
public float upDownRange = 60.0f;
float verticalVelocity = 0;
CharacterController characterController;
// Use this for initialization
void Start () {
Screen.lockCursor = true;
characterController = GetComponent<CharacterController>();
tr = transform;
CharacterController ch = GetComponent<CharacterController>();
dist = ch.height/2; // calculate distance to ground
}
void FixedUpdate (){
float vScale = 1.0f;
float speed = movementSpeed;
if ((Input.GetKey("left shift") || Input.GetKey("right shift")) ch.isGrounded)
{
speed = runSpeed;
}
if (Input.GetKey("c"))
{ // press C to crouch
vScale = 0.5f;
movementSpeed = crchSpeed; // slow down when crouching
}
//characterController.movementSpeed.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;
}
// Update is called once per frame
void Update () {
//Rotation
float rotLeftRight = Input.GetAxis("Mouse X")* mouseSensivity;
transform.Rotate(0, rotLeftRight, 0);
verticalRotation -= Input.GetAxis ("Mouse Y") * mouseSensivity;
verticalRotation = Mathf.Clamp (verticalRotation, -upDownRange, upDownRange);
Camera.main.transform.localRotation = Quaternion.Euler (verticalRotation, 0, 0);
//movement
float forwardSpeed = Input.GetAxis("Vertical") * movementSpeed;
float sideSpeed = Input.GetAxis ("Horizontal") * movementSpeed;
verticalVelocity += Physics.gravity.y * Time.deltaTime;
if(characterController.isGrounded Input.GetButton ("Jump")) {
verticalVelocity = jumpSpeed;
}
Vector3 speed = new Vector3( sideSpeed, verticalVelocity, forwardSpeed );
speed = transform.rotation * speed;
characterController.Move ( speed * Time.deltaTime );
}
}