So currently when I press shift, my players movement speed increases for a period of time (until the value of stamina runs out.) When I am not moving however and am pressing shift, the stamina value runs out anyway.
How can I make it so my stamina only runs out when shift is held down AND my player is using the WASD/Arrow movement keys??
Here is my current movement script:
using UnityEngine;
using UnityEngine.UI;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float MoveSpeed;
public float UpSpeed;
public float shiftSpeed;
public float stamina = 8f;
public Image staminaBar;
bool grounded = true;
bool running = false;
bool levelfinished = false;
bool levelfailed = false;
// Update is called once per frame
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Collectable"))
{
other.gameObject.SetActive(false);
}
}
public void OnCollisionStay(Collision collision)
{
if (collision.gameObject.CompareTag("Ground")) { grounded = true; }
if (collision.gameObject.CompareTag("PlatformMoving")) { grounded = true; }
}
public void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Ground")) { grounded = false; }
if (collision.gameObject.CompareTag("PlatformMoving")) { grounded = false; }
}
void FixedUpdate() //for updating physics
{
Physics.gravity = new Vector3(0, -150f, 0);
if (Input.GetKey("w") || Input.GetKey("up"))
{
rb.AddForce(0, 0, MoveSpeed * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey("s") || Input.GetKey("down"))
{
rb.AddForce(0, 0, -MoveSpeed * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey("a") || Input.GetKey("left"))
{
rb.AddForce(-MoveSpeed / 56, 0, 0 * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey("d") || Input.GetKey("right"))
{
rb.AddForce(MoveSpeed / 56, 0, 0 * Time.deltaTime, ForceMode.VelocityChange);
}
if (rb.position.y < -5f)
{
FindObjectOfType<EndGame>().gameover();
}
}
public void Update()
{
Physics.gravity = new Vector3(0, -150f, 0);
//not firing consistently in fixedupdate
if (Input.GetKeyDown("space") && grounded)
{
rb.AddForce(0, UpSpeed, 0 * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKeyDown("left shift"))
{
MoveSpeed = shiftSpeed;
running = true;
}
if (Input.GetKeyUp("left shift"))
{
MoveSpeed = 105f;
running = false;
}
staminaBar.fillAmount = stamina / 8f;
if (running == false && stamina < 8f) { stamina = stamina + 2 * Time.deltaTime; }
if (running == true && stamina > 0f) { stamina = stamina - 6 * Time.deltaTime; }
if (stamina < 1f) { MoveSpeed = 105f; }
if (stamina != 8f) { shiftSpeed = MoveSpeed; }
if (stamina >= 1f) { shiftSpeed = 155f; }
}
}
I’ve tried a “moving” true and false statements for when keys are pressed etc. but I need a way to check if the player is pressing 1 or more of the movement keys, and when they are not.
Any advice on this is much appreciated ![]()
Best,
J