- Home /
stupid question
Adding stamina to existing script
I found a script that adds sprinting, crouching, etc to CharacterMotor.js. Now i'm trying to add a stamina bar and am having difficulty.
sprint.js
var walkSpeed: float = 8;
var crchSpeed: float = 3;
var runSpeed: float = 16;
var stamina : int = 100;
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 = walkSpeed;
if (ch.isGrounded && Input.GetKey("left shift") || Input.GetKey("right shift")) {
if (stamina != 0) {
speed = runSpeed;
stamina = stamina - 1;
}
}
if (Input.GetKey("left ctrl") || Input.GetKey("right ctrl")) {
h = 0.5 * height;
speed = crchSpeed;
}
chMotor.movement.maxForwardSpeed = speed;
var lastHeight = ch.height;
ch.height = Mathf.Lerp(ch.height, h, 5*Time.deltaTime);
tr.position.y += (ch.height-lastHeight)/2;
if (stamina != 100) {
stamina = stamina + 0.5;
}
}
function OnGUI () {
GUI.Box(Rect(120,Screen.height - 50, 80, 40), "");
GUI.Label(Rect(130,Screen.height - 30, 180, 125), stamina + " / " + "100");
GUI.Label(Rect(130,Screen.height - 50, 180, 125), "Stamina");
}
The GUI and depletion of stamina, works. Recharging stamina, does not work. I would also like to fix stamina decreasing when shift is pressed but the player is not moving.
I don't see where you declared sta$$anonymous$$a (var) in this script
some of the code was cut off, i apologize. it should be correct now
Answer by AlucardJay · Sep 02, 2013 at 10:16 PM
check if one of the movement keys are being pressed :
if (ch.isGrounded && Input.GetKey("left shift") || Input.GetKey("right shift")) {
if (stamina != 0) {
speed = runSpeed;
if ( Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)) {
stamina = stamina - 1;
}
}
}
with the stamina, you are using an integer, therefor you cannot add 0.5, so it doesn't recharge the stamina. Use an integer value (-2 decrease, +1 increase), or declare stamina as a float.
var stamina : float = 100;
Then check with :
if (stamina < 100) {
stamina = stamina + 0.5;
}