好的,我做了一些学习的东西,我需要我的电梯停几秒钟 private IEnumerator ReversePlatform() { Yield return new WaitForSeconds(2); _AccuTime = 0...
好的,我做了一些学习工作,我需要让电梯停几秒钟
private IEnumerator ReversePlatform()
{
yield return new WaitForSeconds(2);
_AccuTime = 0;
speed = -speed;
}
我在这里打电话,我的电梯就开始摇晃并上升,它们不会下降
if (_AccuTime > _RunTime)
{
StartCoroutine("ReversePlatform");
}
else
{
transform.Translate(0, speed * Time.deltaTime, 0);
}
我需要它们上升,停留大约 2 秒,然后持续下降
我需要它们上升,停留大约 2 秒,然后持续下降
和重复协程 Update
总是有点奇怪
[Tooltip("Where to move to (worldspace)")]
[SerializeField]
private Vector3 targetPosition;
[Tooltip("How fast to move (unit/s)")]
[SerializeField]
private float moveSpeed;
[Tooltip("How long to wait on the start/end positions")]
[SerializeField]
private float delay = 2f;
private Vector3 startPosition;
private IEnumerator Start()
{
startPosition = transform.position;
// This is totally fine for a Coroutine as long as you ensure you yield
while(true)
{
// move to target with given speed
yield return MoveTowards(transform, targetPosition, moveSpeed);
// wait for delay
yield return new WaitForSeconds(delay);
// move back to start with given speed
yield return MoveTowards(transform, startPosition, moveSpeed);
// wait for delay
yield return new WaitForSeconds(delay);
}
}
private static IEnumerator MoveTowards(Transform transform, Vector3 target, float moveSpeed)
{
// Vector3 == uses approximation with precision 1e-5
while(transform.position != target)
{
// every iteration moves one step towards the target without overshooting
transform.position = Vector3.MoveTowards(transform.position, target, moveSpeed * Time.deltaTime);
// "pauses" the coroutine, let Unity render this frame
// and continue from here in the next frame
yield return null;
}
// to end with clean values
transform.position = target;
}
注意:如果你想在本地空间移动,只需将所有内容交换 transform.position
为 transform.localPosition