Home > OS >  Slowmotion time limit
Slowmotion time limit

Time:05-07

Ok, so I made the player in my game, go into slowmotion then you hold down the space bar. But I want the player to only be avaliable to be in slowmotion for 5 seconds at a time. After 10 second the player will be avaliable to go into slowmotion again.

Heres the code for the script


public class SlowMotion : MonoBehaviour
{
    public float slowMotionTimescale;

    private float startTimescale;
    private float startFixedDeltaTime;

    void Start()
    {
        startTimescale = Time.timeScale;
        startFixedDeltaTime = Time.fixedDeltaTime;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            StartSlowMotion();
        }

        if (Input.GetKeyUp(KeyCode.Space))
        {
            StopSlowMotion();
        }
    
    }

    private void StartSlowMotion()
    {
        Time.timeScale = slowMotionTimescale;
        Time.fixedDeltaTime = startFixedDeltaTime * slowMotionTimescale;
    }

    private void StopSlowMotion()
    {
        Time.timeScale = startTimescale;
        Time.fixedDeltaTime = startFixedDeltaTime;
    }
} ```

CodePudding user response:

You can use IEnumerator to run time-dependent methods. The method description is as follows:

public bool inTimer; // are slow motion is in timer?
public IEnumerator StartTimer()
{
    inTimer = true;
    
    StartSlowMotion();
    
    yield return new WaitForSeconds(5f); // wait to end slow motion

    StopSlowMotion();
    
    yield return new WaitForSeconds(5f); // wait time to finish
    
    inTimer = false;
}

In addition, you need to consider the condition not in timer.

if (Input.GetKeyDown(KeyCode.Space) && !inTimer)
{
    StartCoroutine(StartTimer()); // how to run timer
}
  • Related