Hi guys. I’m trying to create a script where the character moves from 1 waypoint to the next but I am unable to use the MoveTowards feature properly as the character’s movement combines both target’s coordinates instead of going to each target individually before moving on to the next point.
public Transform target1;
public Transform target2;
public float speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
MoveToTarget ();
}
void MoveToTarget(){
float step = speed * Time.deltaTime;
for (int i = 1; i < 3; i++) {
if (i == 1){
transform.position = Vector3.MoveTowards (transform.position, target1.position, step);
}else if(i == 2){
transform.position = Vector3.MoveTowards (transform.position, target2.position, step);
}
}
}
Your for loop is moving towards both your targets every frame. There’s nothing there telling it to just move towards one or the other, it will always move towards both.
Here’s an freehand implementation you can study and try.
public class MoveToRandomTarget : MonoBehaviour
{
public Transform[] targets; // Fill with random waypoints
private Transform currentTarget;
public float speed = 1f;
private void Start()
{
FindNewTarget();
}
private void FindNewTarget()
{
// Pick one of the targets at random.
currentTarget = targets[Random.Range(0, targets.Length)];
}
private void Update()
{
// Move towards currentTarget
transform.position = Vector3 MoveTowards(transform.position, currentTarget.position, speed * Time.deltaTime);
// See if we have reached currentTarget and if so find another.
Vector3 difference = transform.position - currentTarget.position;
float sqrDistance = difference.sqrMagnitude;
if (sqrMagnitude < Mathf.Epsilon)
{
FindNewTarget();
}
}
}
Beware though, modifying the position of a transform does not take any physics interaction into consideration. If you need your object to be constrained by physics, you also need to move it using physics. If you need your object to move around obstacles you will need to make use of pathfinding like @ suggested.