Ssiro
Ssiro

Reputation: 135

How to get smooth slow motion in Unity3D

Im trying to get a slow motion on the game im making but it looks realy laggy. Im using the FPS controller from the standard assets given by unity.I attached this script to it :

function Update () 
{
    if (Input.GetKeyDown ("q"))
    {
        Time.timeScale = 0.5;
    }

    if (Input.GetKeyDown ("e")) 
    {
        Time.timeScale = 2.0;
    }

    if (Input.GetKeyDown ("t")) 
    {
        Time.timeScale = 1.0;
    }
}

I know this is a similar question to this one http://answers.unity3d.com/questions/39279/how-to-get-smooth-slow-motion.html

but the fixes given on that question won't work.I tried adding a rigidbody to it and putting the Interpolation to Interpolate but it doesn't do anything.(I removed the tick from "Use Gravity" because the character started flying).Im new in unity and scripting so please go easy on me.

Thank you.

Upvotes: 4

Views: 11083

Answers (3)

Jay Rojivadiya
Jay Rojivadiya

Reputation: 31

You just need to call SetTimeScale Method as target timescale as argument :)

using UnityEngine;
public class TimeScaleSmooth : MonoBehaviour
{
    public float targetTimeScale = 1;
    public float speed = 1;

    void Update()
    {
        Time.timeScale = Mathf.MoveTowards(Time.timeScale, targetTimeScale, 
        Time.unscaledDeltaTime * speed);
        //0.02 is default fixedDeltaTime
        Time.fixedDeltaTime = timeScale * 0.02f;
        //FOR TEST
        if (Input.GetKeyDown(KeyCode.A))
        {
            SetTimeScale(1);
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            SetTimeScale(0.2f);
        }
    }

    public void SetTimeScale(float timeScale)
    {
        targetTimeScale = timeScale;
    }
}
  • Note that we used Time.unscaledDeltaTime which is independent of timescale.
  • You can tweak transition time using speed.

Upvotes: 1

g8minhquan
g8minhquan

Reputation: 732

You should change Time.fixedDeltaTime as well:

function Update () {
   if (Input.GetKeyDown ("q")){
      Time.timeScale = 0.5;
      Time.fixedDeltaTime = 0.02F * Time.timeScale;
   }
}

To return it to normal motion again you should call these two lines

      Time.timeScale = 1;
      Time.fixedDeltaTime = 0.02F * Time.timeScale;

Upvotes: 6

galika1080
galika1080

Reputation: 1

This is actually insanely easy. In fact, you don't even have to code anything! Just go into every rigidbody in the scene, and change the interpolation mode to "interpolate" or "extrapolate". They mean very different things, but both have the end result of perfectly smooth slow-motion.

Upvotes: 0

Related Questions