简体   繁体   中英

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);
    }
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM