mdatsev
mdatsev

Reputation: 3879

Moving a 3d object back and forth between points

I tried to make a script that moves an object back and forth between two points. But it just flies in the ifinity. I tried to find the problem whole evening but idk. here is the code:

using UnityEngine;

public class MovementBetweenPoints : MonoBehaviour {
    public Transform[] keyPoints;
    public float speed;
    private int currentKeyPoint;


    // Use this for initialization
    void Start () 
    {
        transform.position = keyPoints[0].position;
        currentKeyPoint = 1;
    }

    // Update is called once per frame
    void Update () 
    {

        if (transform.position == keyPoints[currentKeyPoint].position)
        {
            currentKeyPoint++;
        }

        if (currentKeyPoint >= keyPoints.Length)
        {
            currentKeyPoint = 0;
        }

        transform.position = Vector3.MoveTowards(transform.position, keyPoints[currentKeyPoint].position, speed * Time.deltaTime);
    }
}

Upvotes: 2

Views: 1109

Answers (2)

I'm sure the problem comes with this part of the code where you check if the position of the object is equal at some waypoint. Instead of:

if (transform.position == keyPoints[currentKeyPoint].position)
{
     currentKeyPoint++;
}

try to do something less agressive, and give a bit of margin like:

if (Vector3.Distance(transform.position - keyPoints[currentKeyPoint].position) <= min_Distance)
{
     currentKeyPoint++;
}

because it's almost impossible that two objects with different speeds match at the same point. Instead of this, you'll use min_Distance to check it.

Upvotes: 2

Ivan Alvarez
Ivan Alvarez

Reputation: 56

Your script works fine as it is. you need to make sure that speed is set to a value greater than 0 in the inspector, and that the keypoints array contains some gameobjects in the inspector too, and you are good to go

Upvotes: 2

Related Questions