Unity3d 为运动编写IEnumerator

Unity3d 为运动编写IEnumerator,unity3d,Unity3d,我想编写一个IEnumerator,在指定的时间按所需的距离移动。我曾尝试为此编写代码,但这是以不同的方式运行的 float moveDistance=1f; float moveSpeed=5f; float elapsedDistance = 0f; while (elapsedDistance <= moveDistance) { elapsedDistance += Time.deltaTime * moveSp

我想编写一个IEnumerator,在指定的时间按所需的距离移动。我曾尝试为此编写代码,但这是以不同的方式运行的

     float moveDistance=1f;
     float moveSpeed=5f;
     float elapsedDistance = 0f;

     while (elapsedDistance <= moveDistance)
     {
         elapsedDistance += Time.deltaTime * moveSpeed;

         Vector3 cubeLocalPosition = transform.localPosition;
         cubeLocalPosition.y += Time.deltaTime * moveDistance;
         transform.localPosition = cubeLocalPosition;
         yield return null;
     }
float-moveDistance=1f;
浮动速度=5f;
浮动滞后距离=0f;

当(elapsedDistance跟随您自己的旋转时,您计算要移动的最终点 之后呢,, 您可以使用或在指定的时间内移动..因此移动速度会根据所需的时间进行调整

var endpoint = transform.position + transform.forward.normalized * distance;
StartCoroutine(MoveToPosition(transform, endpoint, 3f)
:
:
public IEnumerator MoveToPosition(Transform transform, Vector3 positionToGO, float timeToMove)
{
  var currentPos = transform.position;
  var t = 0f;
  while (t < 1f)
  {
    t += Time.deltaTime / timeToMove;
    transform.position = Vector3.Lerp(currentPos, positionToGO, t);
    yield return null;
  }
  transform.position = positionToGO;
}
var endpoint=transform.position+transform.forward.normalized*距离;
开始例程(移动位置(变换、端点、3f)
:
:
公共IEnumerator移动位置(变换、矢量3位置移动、浮点时间移动)
{
var currentPos=变换位置;
var t=0f;
而(t<1f)
{
t+=Time.deltaTime/timeToMove;
transform.position=Vector3.Lerp(currentPos,positionToGO,t);
收益返回空;
}
transform.position=positionToGO;
}

你的while循环条件使用了elapseddance,它随着移动速度的增加而增加。后者是5,因此它将是1/1/5秒。你的对象可能只移动了0.2个单位

您应该使用Mathf.Lerp或moveToward

float distance = 1f;
float time = 0f;
float period = 1f; // how long in second to do the whole movement
yield return new WaitUntil(()=>
{
    time += Time.deltaTime / period;
    float movement = Mathf.Lerp(0f, distance, time);
    Vector3 cubeLocalPosition = transform.localPosition;
    cubeLocalPosition.y += movement;
    transform.localPosition = cubeLocalPosition;
    return time >= 1f;
});

您需要更改IEnumerator的返回值,以便让协程等待从最后一帧开始的时间延长。您可以使用来执行此操作

返回新的WaitForSeconds(Time.deltaTime);

这样,您就“模拟”了回调的beaviour(更新函数中的逻辑).

这个物体是否有刚体?你正在经历什么样的行为?它到底在移动吗?要最终确定答案,请记住,如果你原来的问题已经解决,请接受并投票支持答案,如果你还有其他问题,请问一个新问题: