- Home /
How to disable sprinting when slider reaches zero.
So I need some help...
I have my controls so that when the player presses the shift button while moving, the character begins sprinting. I've also managed to have the stamina bar in a way so that the filling gradually goes down when holding shift. My problem is that I'm not sure how to edit my code to where when the stamina bar reaches 0, the player can no longer sprint.
Here's the Stamina Bar code:
{
public Slider slider;
public void SetMaxStamina(int stamina)
{
slider.maxValue = stamina;
slider.value = stamina;
}
public void SetStamina(int stamina)
{
slider.value = stamina;
}
public int maxStamina = 200;
public int currentStamina;
public StaminaBar staminaBar;
void Start()
{
currentStamina = maxStamina;
staminaBar.SetMaxStamina(maxStamina);
}
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
TakeDamage(20);
}
}
void TakeDamage(int damage)
{
currentStamina -= damage;
staminaBar.SetStamina(currentStamina);
}
}
Here's the player movement script:
{ private float jumpSpeed = 5; private Rigidbody rigidBody; private bool onGround = true; private const int MAX_JUMP = 2; private int currentJump = 0;
public float walkSpeed;
public float sprintSpeed;
public GameObject slider;
// Use this for initialization
void Start()
{
rigidBody = GetComponent<Rigidbody>();
walkSpeed = 5f;
sprintSpeed = 10f;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space") && (onGround || MAX_JUMP > currentJump))
{
rigidBody.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
onGround = false;
currentJump++;
}
//This is the part I need help with
StopSprinting();
//I'm not sure how to properly add "if" statements, if that's what I need to do
transform.Translate(walkSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, walkSpeed * Input.GetAxis("Vertical") * Time.deltaTime);
//Sprinting
if (Input.GetKey(KeyCode.LeftShift))
{
walkSpeed = sprintSpeed;
}
else
{
walkSpeed = walkSpeed;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
walkSpeed = 5f;
}
void StopSprinting()
{
}
}
void OnCollisionEnter(Collision collision)
{
onGround = true;
currentJump = 0;
}
}
If you need any more information, please me know. Thank you.
You need to take your void StopSprinting()
out of the Update function.
Answer by tuinal · Jun 13, 2020 at 08:06 AM
Why not just...
if (Input.GetKey(KeyCode.LeftShift))
to
if (Input.GetKey(KeyCode.LeftShift)&&stamina>0)
I've tried replacing the line of script on both of them, but neither one made a difference, unfortunately. Thank you for trying, though
Your answer
Follow this Question
Related Questions
What's wrong with my sprinting logic? 1 Answer
Sprinting animation 1 Answer
How do I script so my character Jumps farther when Running? 1 Answer
Reducing an integer by X per second 1 Answer
Mid air "sprint" 2 Answers