使用mathf.Repeat并指定开始时间

时间:2017-01-11 20:03:37

标签: c# unity3d unity5

基本上在我的项目中,我有一架飞机,每当他到达 b a 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 - >上等待5秒移动之前开始位置,我没有记住其他解决方案然后curoutine,使用以下代码的curoutine,运动不顺利,有点奇怪它只是从1位置到另一个它似乎不像一个运动。

1 个答案:

答案 0 :(得分:0)

您可以在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;
 }