Unity 简单的暂停功能实现

Unity中可以通过Time.timeScale来控制时间流逝的速率,因此通过Time.timeScale = 0f即可实现简单的暂停功能。

不过由于Time.timeScale会对全局造成影响,有的时候我们可能希望在暂停中一部分物体可以保持运动——比如我希望我的塔防游戏暂停时可以继续移动摄像机,这种时候我们可以用Time.realtimeSinceStartup。它的值是游戏开始以来的实际时间,不受Time.timeScale影响。

举个例子,这是我的摄像机移动代码:

 void Update()
{
     int direction = 0;
     if (Input.GetKey(KeyCode.E)) direction = 1;
     else if (Input.GetKey(KeyCode.Q)) direction = -1;
     angles.y += angleSpeed * direction * Time.deltaTime;
     transform.rotation = Quaternion.Euler(angles);
     Vector3 input = Vector3.zero;
     input.x = Input.GetAxis("Horizontal");
     input.z = Input.GetAxis("Vertical");
     input = Vector3.ClampMagnitude(input, 1f);
     Vector3 lookForward = transform.forward;
     lookForward.y = 0;
     transform.position += Quaternion.LookRotation(lookForward) * input * speed * Time.deltaTime;
 }

为了能够在暂停时移动,我需要记录上一次调用update的时间,再将Time.deltaTime换成Time.realtimeSinceStartup - lastTime

修改后的代码如下:

void Update()
{
    int direction = 0;
    if (Input.GetKey(KeyCode.E)) direction = 1;
    else if (Input.GetKey(KeyCode.Q)) direction = -1;
    angles.y += angleSpeed * direction * (Time.realtimeSinceStartup - lastTime);
    transform.rotation = Quaternion.Euler(angles);
    Vector3 input = Vector3.zero;
    input.x = Input.GetAxisRaw("Horizontal");
    input.z = Input.GetAxisRaw("Vertical");
    input = Vector3.ClampMagnitude(input, 1f);
    Vector3 lookForward = transform.forward;
    lookForward.y = 0;
    transform.position += Quaternion.LookRotation(lookForward) * input * speed * (Time.realtimeSinceStartup - lastTime);
    lastTime = Time.realtimeSinceStartup;
}

可能有人注意到我把Input.GetAxis换成了Input.GetAxisRaw。根据我的测试,Input.GetAxis应该是会受Time.timeScale影响,换成Input.GetAxisRaw就没事了,不过缺点是不会像Input.GetAxis那样有个过渡了。

实际效果演示:

posted @ 2022-05-27 14:26  樱与梅子  阅读(2561)  评论(0)    收藏  举报