在最小和最大之间沿x轴移动

时间:2017-01-11 18:05:18

标签: c# unity3d unity5

我有一个在最小值和最大值之间移动的平面,它在2点之间反弹,但我不希望这种影响,我希望飞机到达某个点,然后在开始点再次开始。我怎么能这样做?

此刻我尝试了这个:

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 Update()
    {


        //get a value between 0 and 1
        float normalizedTime = Mathf.PingPong(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 
        if (transform.position.x <= 8f)
            rb.MovePosition(new Vector3(MaxX, rb.position.y, rb.position.z));
        else
            rb.MovePosition(new Vector3(xPosition, rb.position.y, rb.position.z));
    }
}

1 个答案:

答案 0 :(得分:1)

使用Mathf.Repeat代替PingPong