Unity Time.timeScale
测试代码 :
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using UnityEngine.UI; 5 6 public class ObjectController : MonoBehaviour { 7 8 public GameObject cube; 9 public GameObject capsule; 10 public GameObject sphere; 11 public Camera mainCamera; 12 13 private Vector3 cubeBeginCoordinate = new Vector3(-10,3,0); 14 private Vector3 cubeEndCoordinate = new Vector3(10, 3, 0); 15 private Vector3 cubeCurrentCoordinate; 16 17 private Vector3 capsuleBeginCoordinate = new Vector3(-10, 0, 0); 18 private Vector3 capsuleEndCoordinate = new Vector3(10, 0, 0); 19 private Vector3 capsuleCurrentCoordinate; 20 21 private Vector3 sphereBeginCoordinate = new Vector3(-10, -3, 0); 22 private Vector3 sphereEndCoordinate = new Vector3(10, -3, 0); 23 private Vector3 sphereCurrentCoordinate; 24 25 private int timeScaled = 1; 26 27 private float interpolationForSphere = 0.001f; 28 private float interpolationForCapsule = 0.001f; 29 30 // Use this for initialization 31 void Start () { 32 cubeCurrentCoordinate = cubeBeginCoordinate; 33 capsuleCurrentCoordinate = capsuleBeginCoordinate; 34 sphereCurrentCoordinate = sphereBeginCoordinate; 35 36 } 37 38 // Update is called once per frame 39 void Update () { 40 // 以游戏运行时间作为插值的情况,测试 Time.timeScale 对 Time.time 的影响 41 if (!cube.transform.position.Equals(cubeEndCoordinate)) { 42 cube.transform.position = Vector3.Lerp(cubeCurrentCoordinate, cubeEndCoordinate, Time.time / 100); 43 } 44 45 // 自定义插值,测试 Time.timeScale 对 Update() 函数的影响 46 sphere.transform.position = Vector3.Lerp(sphereCurrentCoordinate, sphereEndCoordinate, interpolationForSphere); 47 interpolationForSphere += 0.001f; 48 if (sphere.transform.position.Equals(sphereEndCoordinate)) { 49 interpolationForSphere = 0.001f; 50 sphereCurrentCoordinate = sphereBeginCoordinate; 51 } 52 } 53 54 private void FixedUpdate() { 55 // 自定义插值,测试 Time.timeScale 对 FixedUpdate() 函数的影响 56 capsule.transform.position = Vector3.Lerp(capsuleCurrentCoordinate, capsuleEndCoordinate, interpolationForCapsule); 57 interpolationForCapsule += 0.001f; 58 if (capsule.transform.position.Equals(capsuleEndCoordinate)) { 59 interpolationForCapsule = 0.001f; 60 capsuleCurrentCoordinate = capsuleBeginCoordinate; 61 } 62 } 63 64 private void OnGUI() { 65 if (GUI.Button(new Rect(10, 40, 130, 20), "Time Scaled Plus")) { 66 timeScaled = (timeScaled + 1) % 100; 67 Time.timeScale = timeScaled; 68 } 69 70 if (GUI.Button(new Rect(10, 70, 130, 20), "Time Scaled Sub")) { 71 if (timeScaled == 0) { 72 timeScaled = 99; 73 } else { 74 timeScaled = (timeScaled - 1) % 100; 75 } 76 77 Time.timeScale = timeScaled; 78 } 79 80 if (GUI.Button(new Rect(10, 100, 130, 20), "Reset Scaled")) { 81 timeScaled = 0; 82 Time.timeScale = timeScaled; 83 } 84 GUI.Button(new Rect(10, 10, 100, 20), timeScaled.ToString()); 85 } 86 }
测试截图:
场景视图中 ,左上角顶部的值是 Time.timeScale 的值
学习记录,方便复习