I am defining three gameObject points where a sphere gameObject should travel from one position to another in a loop, such that 1-2-3-1-2-3....(as in a triangle). I am able to achieve the movement with Vector3.MoveTowards()
function but it only takes in 2 points. Is there a way to achieve the same with multiple points? (atleast 3 or more)
public class SlideBetweenPoints : MonoBehaviour
{
public Transform pointA, pointB, pointC;
public float speed;
void Update ()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(pointA.position , pointB.position , step);
}
}
Yes simply move towards one point and when you reached it go to the next one.
Note that currently you are always starting again from pointA
. In order to continuously move towards a target position you have to rather use
transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
I would rather use a more general List like
public class SlideBetweenPoints : MonoBehaviour
{
public List<Transform> points;
public float speed;
private int index;
void Update ()
{
transform.position = Vector3.MoveTowards(transform.position, points[index].position, speed * Time.deltaTime);
if(transform.position == points[index].position)
{
// increase index with wrap around
index = (index + 1) % points.Count;
}
}
}
Where transform.position == points[index]
uses a precision of 1e-5
for equality. If you really need it you could also check for exact matching positions:
if(Mathf.Approximately(0, (transform.position- points[index].position).sqrMagnitude))
{
index = (index + 1) % points.Count;
}
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.