My code is When the player presses X on the keyboard he sprints. It works
But I want the player to get tired after running for a few seconds than recharges? How do I do that? Or can someone provide me a script i can use?
Note: Im a Noob at Programming
using UnityEngine;
using System.Collections;
public class HoldButtonRun : MonoBehaviour {
public MoveForward moveForwardScript;
// Use this for initialization
void Start () {
moveForwardScript = GameObject.Find("Player").GetComponent<MoveForward>();
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.X))
{
moveForwardScript.speed = 10.0f;
}
else
{
moveForwardScript.speed = 3.0f;
}
Time.timeScale = 3.0f;
}
}
Here’s what I would do. I think the comments I added will be enough to get what’s going on :
using UnityEngine;
using System.Collections;
public class HoldButtonRun : MonoBehaviour {
public MoveForward moveForwardScript;
// time the player is allowed to run continuously until he get tired
public float timeUntilTired = 5f;
// time the player must wait (and not run) until he can run again
public float restDuration = 10f;
// current running time
private float runningTime = 0f;
// current resting time
private float restingTime = 0f;
// Use this for initialization
void Start () {
moveForwardScript = GameObject.Find("Player").GetComponent<MoveForward>();
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.X))
{
// the player is running (or trying to), reset the restingTime
restingTime = 0f;
// increment the running time
runningTime += Time.deltaTime;
if (runningTime > timeUntilTired) {
moveForwardScript.speed = 3.0f;
}
else {
moveForwardScript.speed = 10.0f;
}
}
else
{
// the player is walking, reset the running time
runningTime = 0f;
// increment the restingTime
restingTime += Time.deltaTime;
// if the player didn't run for "restDuration", reset runningTime
// We can also reset restingTime as values above restDuration have no relevance
if (restingTime > restDuration) {
runningTime = 0f;
restingTime = 0f;
}
moveForwardScript.speed = 3.0f;
}
Time.timeScale = 3.0f;
}
}