- Home /
I am trying to make a stamina bar and it won't drain no matter what i try.
I made a stamina bar and I want it to go down by a certain amount when you are holding shift and then go up when isRunning = false, which is set false when you lift up from the space. I can not set it to go down every second while holding the bar though, it only goes down once. Can someone please help me? Here's the script:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
//SPEED AND SUCH
public float speed = 6.0f;
public float strafeSpeed = 5.8f;
public float jumpSpeed = 8.0f;
public float gravity = 18.125f;
private Vector3 moveDirection = Vector3.zero;
private bool grounded = false;
private bool isRunning = false;
//STAMINA BAR
public GUIStyle staminaBar;
private float maxStamina = 100.0f;
private float curStamina = 100.0f;
private float staminaBarLength;
void Start ()
{
staminaBarLength = 85;
}
void Update ()
{
if (grounded)
{
moveDirection = new Vector3(Input.GetAxis ("Horizontal"),0,Input.GetAxis ("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if(Input.GetKeyDown (KeyCode.LeftShift))
{
speed = 10.00f;
isRunning = true;
AdjustCurrentStamina(-1);
}
else if(Input.GetKeyUp (KeyCode.LeftShift))
{
speed = 6.0f;
isRunning = false;
}
else if(isRunning == false)
{
AdjustCurrentStamina (1);
}
}
if (grounded)
{
if(Input.GetKey (KeyCode.Space))
{
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
var Controller = GetComponent<CharacterController> ();
var flags = Controller.Move (moveDirection * Time.deltaTime);
grounded = (flags & CollisionFlags.CollidedBelow) != 0;
AdjustCurrentStamina (0);
}
void OnGUI()
{
GUI.Box (new Rect (355, 476, staminaBarLength, 125), "Stamina", staminaBar);
}
void AdjustCurrentStamina(int adj)
{
curStamina += adj * Time.deltaTime;
if(curStamina <0)
curStamina = 0;
if(curStamina > maxStamina)
curStamina = maxStamina;
if (curStamina < 100)
if(maxStamina <1)
maxStamina = 1;
staminaBarLength =(85) * (curStamina / (float)maxStamina);
}
}
Any help is appreciated!
Answer by Zentiu · Mar 16, 2014 at 04:07 PM
try this in your AdjustCurrentStamina method:
if(isRunning)
{
curStamina -= Time.deltaTime;
}
when you stop running (!isRunning) or (isRunning == false) it should not reduce stamina anymore.
when I did my own stamina mechanic/method I preferred this mechanic then telling it to remove a certain value.
you don't really need a value like an int and pass it into your method. besides, 2 different structs don't always work well together. it either needs to be (float (against) float) or (int (against) int).
however, if you prefer your way try this:
//in your sta$$anonymous$$a method
curSta$$anonymous$$a += (float)adj * Time.deltaTime;