I have a script to make my character slower if he has less energy and to recover the enrgy while walking and crouching. I’ve fixed it.
Here’s the script.
var walkSpeed : float = 5;
var crchSpeed : float = 3;
static var stamina : float = 40;
var drainSpeed : float = 1.5;
var crouchRecovery : float = 1.5;
var walkRecovery : float = 1;
static var walking : boolean = true;
static var running : boolean = false;
static var crouched : boolean = false;
static var moving : boolean = false;
static var cantMove : boolean = false;
private var Speed : float = 1;
private var chMotor: CharacterMotor;
private var ch: CharacterController;
private var tr: Transform;
private var height: float;
function Start(){
chMotor = GetComponent(CharacterMotor);
tr = transform;
ch = GetComponent(CharacterController);
height = ch.height;
}
function Update(){
var h = height;
var speed = Speed;
var runSpeed : float = stamina/4;
if (cantMove){
Time.timeScale = 0.0;
}else{
Time.timeScale = 1.0;
}
if (Input.GetButton("Jump")){
crouched = false;
}
if (Input.GetKey("left shift") || Input.GetKey("right shift")){
running = true;
}else{
running = false;
}
if (Input.GetAxis("Horizontal") || Input.GetAxis("Vertical")){
moving = true;
}else{
moving = false;
}
if (!running && !crouched){
speed = walkSpeed;
walking = true;
}else{
walking = false;
}
if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl)){
crouched = !crouched;
}
if (crouched){
h = 0.5 * height;
speed = crchSpeed;
}
if (running && moving){
Draining();
speed = runSpeed;
crouched = false;
}else{
Recovering();
}
if (stamina<24){
audio.Play();
}
chMotor.movement.maxForwardSpeed = speed;
chMotor.movement.maxSidewaysSpeed = speed -0.5;
chMotor.movement.maxBackwardsSpeed = speed -1;
var lastHeight = ch.height;
ch.height = Mathf.Lerp(ch.height, h, 5*Time.deltaTime);
tr.position.y += (ch.height-lastHeight)/2;
}
function Draining(){
stamina -= drainSpeed * Time.deltaTime;
if (stamina <= 24){
stamina = 24;
audio.Play();
}
}
function Recovering(){
if (walking && !moving){
stamina += walkRecovery * Time.deltaTime;
}
if (crouched && !moving){
stamina += crouchRecovery * Time.deltaTime;
}
if (walking){
stamina += 0.5 * walkRecovery * Time.deltaTime;
}
if (crouched){
stamina += 0.5 * crouchRecovery * Time.deltaTime;
}
if (stamina >= 40){
stamina = 40;
}
}