- Home /
Time Freezer
so i want to make a time freezer in a script which enemies has it to move up and down, and i want the script to smoothly (smoothly really) move slower and slower and then stop, same as unfreezing time.
private Vector3 pos1;
private Vector3 pos2;
public Vector3 posDiff = new Vector3(0f, 0f, 20f);
public float speed = 1.0f;
public bool Freezeable = true;
public GameObject PistonObject;
void Start()
{
pos1 = transform.position;
pos2 = transform.position + posDiff;
}
bool Freeze = false;
void Update()
{
if (Freeze == false)
{
transform.position = Vector3.Lerp(pos1, pos2, Mathf.PingPong(Time.time * speed, 1.0f));
}
if (Freeze == false && Input.GetKeyDown(KeyCode.E) && Freezeable == true)
{
speed -= Time.deltaTime;
Freeze = true;
}
else if (Freeze == true && Input.GetKeyDown(KeyCode.E) && Freezeable == true)
{
speed += Time.deltaTime;
Freeze = false;
}
that is what i've done so far.
the problem is, -= and += doesn't smoothly change value.
the freezeable bool is just to make some enemies don't be affected (immune enemies.)
Answer by Chris_Payne_QS · Apr 29, 2020 at 02:08 PM
On the frame that you press E it will subtract Time.deltaTime (a barely noticeable change) and set Freeze to true so your object stops moving instantly. You need to wait until speed reaches zero before you stop updating the position.
I would store a speedTarget variable and constantly lerp speed towards that value - then you only have to set speedTarget to 0 or 1 and the transition will happen automatically (even if interrupting an existing transition).
Also remove the Freeze flag and use if (speed>0f)
to determine whether to update position.
Example:
public float speed = 1f;
private float speedTarget = 1f;
void Update()
{
speed = Mathf.MoveTowards( speed, speedTarget, Time.deltaTime );
if (speed>0f)
{
// do movement
}
if (Freezable)
{
if (Input.GetKeyDown(KeyCode.E))
{
speedTarget = 1f - speedTarget; // 0 becomes 1, 1 becomes 0
}
}
}
i did not see my Freeze mistake, but for the other stuff you said i don't really understand. maybe a link to the unity manual?
I added a code fragment to the answer, hope that helps...
Your answer
![](https://koobas.hobune.stream/wayback/20220612232804im_/https://answers.unity.com/themes/thub/images/avi.jpg)