C# 使用mathf。重复并指定开始时间

C# 使用mathf。重复并指定开始时间,c#,unity3d,unity5,C#,Unity3d,Unity5,基本上,在我的项目中,我有一个平面,每次我都想从位置a到b做一个特定的运动,当他到达b时,他又回到a 所以我做了这个: public class pingPongPlane : MonoBehaviour { public float MinX = -10.2f; // y position of start point public float MaxX = 55f; // y position of end point public float PingPongTi

基本上,在我的项目中,我有一个平面,每次我都想从位置ab做一个特定的运动,当他到达b时,他又回到a

所以我做了这个:

public class pingPongPlane : MonoBehaviour {

    public float MinX = -10.2f; // y position of start point
    public float MaxX = 55f; // y position of end point
    public float PingPongTime = 1f; // how much time to wait before reverse
    public Rigidbody rb; // reference to the rigidbody

    void Start()
    {
        StartCoroutine( ShowEvent() ) ;
    }

    IEnumerator ShowEvent(){
        while (true) {
            yield return new WaitForSeconds (4f);
            //get a value between 0 and 1
            float normalizedTime = Mathf.Repeat (Time.time, PingPongTime) / PingPongTime;
            //then multiply it by the delta between start and end point, and add start point to the result
            float xPosition = normalizedTime * (MaxX - MinX) + MinX;
            //finally update position using rigidbody 
            rb.MovePosition (new Vector3 (xPosition, rb.position.y, rb.position.z));
        }
    }
}

在更新和没有curoutine的情况下,我有了我想要的移动,但我的飞机在移动之前应该在a->begin position上等待5秒,我不记得还有其他解决方案,然后使用curoutine,使用curoutine和以下代码,移动不平稳,有点奇怪,它只是从一个位置移动到另一个位置,看起来不像是移动。

您可以在
Update
中进行移动,但使用
if
语句和等待所需时间的
yield
将其停止几秒钟

public bool CanStart = false;

 void Start ()
 {
     StartCoroutine (StartMove());
 }

 void Update ()
 {
     if (CanStart == true)
     {
           //get a value between 0 and 1
            float normalizedTime = Mathf.Repeat (Time.time, PingPongTime) / PingPongTime;
            //then multiply it by the delta between start and end point, and add start point to the result
            float xPosition = normalizedTime * (MaxX - MinX) + MinX;
            //finally update position using rigidbody 
            rb.MovePosition (new Vector3 (xPosition, rb.position.y, rb.position.z))

     }

 }

 IEnumerator StartMove()
 {
     yield return new WaitForSeconds (5.0f);
     CanStart = true;
 }

不工作,我不想移动物体,我想收缩直到它消失,移动物体