【发布时间】:2020-05-03 13:22:30
【问题描述】:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Turn_Move : MonoBehaviour {
public int TurnX;
public int TurnY;
public int TurnZ;
public int MoveX;
public int MoveY;
public int MoveZ;
public bool World;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (World == true) {
transform.Rotate(TurnX * Time.deltaTime,TurnY * Time.deltaTime,TurnZ * Time.deltaTime, Space.World);
transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.World);
}else{
transform.Rotate(TurnX * Time.deltaTime,Random.Range(3,300) * Time.deltaTime,TurnZ * Time.deltaTime, Space.Self);
transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.Self);
}
}
}
这是随机部分:
Random.Range(3,300)
但是因为它改变随机数的速度太快了,所以几乎看不到变化。 我想以某种方式做到这一点,例如,如果下一个随机数将以这个速度数字保持 5 秒,然后移动到下一个随机数并再次保持这个数字 5 秒,依此类推。
试过这个:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Turn_Move : MonoBehaviour {
public int TurnX;
public int TurnY;
public int TurnZ;
public int MoveX;
public int MoveY;
public int MoveZ;
public bool World;
private bool IsGameRunning = false;
// Use this for initialization
void Start ()
{
IsGameRunning = true;
StartCoroutine(SpeedWaitForSeconds());
}
// Update is called once per frame
void Update () {
}
IEnumerator SpeedWaitForSeconds()
{
var delay = new WaitForSeconds(3);//define ONCE to avoid memory leak
while (IsGameRunning)
{
if (World == true)
{
transform.Rotate(TurnX * Time.deltaTime, TurnY * Time.deltaTime, TurnZ * Time.deltaTime, Space.World);
transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.World);
}
else
{
transform.Rotate(TurnX * Time.deltaTime, Random.Range(3, 300) * Time.deltaTime, TurnZ * Time.deltaTime, Space.Self);
transform.Translate(MoveX * Time.deltaTime, MoveY * Time.deltaTime, MoveZ * Time.deltaTime, Space.Self);
}
yield return delay;//wait
}
}
}
但这只是每 3 秒旋转一次对象。而不是一直旋转它,速度每 3 秒改变一次。
【问题讨论】:
-
我通常是桌面或 Web 开发人员,但是当我需要使用 c# 延迟我的应用程序中的任何进程时,我使用 System.Threading.Thread.Sleep(),docs.microsoft.com/en-us/dotnet/api/…
-
不要在 Unity 中使用类似的线程。使用协程。