Move GameObject back and forth

后端 未结 1 1856
北荒
北荒 2020-12-02 01:18

I got an Object that I want to move up to Point A and when it reaches Point A it should move to Point B. When it reaches Point B it should move back to Point A.

I th

相关标签:
1条回答
  • 2020-12-02 02:12

    There are many ways to do this but Mathf.PingPong is the easiest and the simplest way to accomplish this. Use Mathf.PingPong to get number between 0 and 1 then pass that value to Vector3.Lerp. That's it.

    Mathf.PingPong will automatically return value will that will move back and forth between 0 and 1. Read the linked documentation for more info.

    public float speed = 1.19f;
    Vector3 pointA;
    Vector3 pointB;
    
    void Start()
    {
        pointA = new Vector3(0, 0, 0);
        pointB = new Vector3(5, 0, 0);
    }
    
    void Update()
    {
        //PingPong between 0 and 1
        float time = Mathf.PingPong(Time.time * speed, 1);
        transform.position = Vector3.Lerp(pointA, pointB, time);
    }
    
    0 讨论(0)
提交回复
热议问题