Search Unity

Move objects array with points array

Discussion in 'Scripting' started by nbg_yalta, May 28, 2015.

  1. nbg_yalta

    nbg_yalta

    Joined:
    Oct 3, 2012
    Posts:
    378
    Hi all, I want to move my objects with waypoints array, some thing like this:

    in start I'm placing objects to start positions:


    Code (csharp):
    1.  
    2. for(int i = 0; i < points.Length-2; i++)
    3. {
    4. objects[i].position = points[i].position;
    5. }
    6.  
    7.  
    But cannot figure out how to move them
     
  2. nbg_yalta

    nbg_yalta

    Joined:
    Oct 3, 2012
    Posts:
    378
    Ok, here is what I have for now:
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class MoveTest : MonoBehaviour {
    6.   public Transform[] obj;
    7.   public Transform[] points;
    8.   public int index;
    9.  
    10.    void Start ()
    11.   {
    12.   for (int i = 0; i < points.Length - 8; i++)
    13.   {
    14.   obj.position = points.position;
    15.   }
    16.    }
    17.  
    18.  
    19.   void Update()
    20.   {
    21.   if (Input.GetMouseButton(0))
    22.   Move();
    23.   }
    24.  
    25.  
    26.   void Move()
    27.   {
    28.   for (int i = 0; i < obj.Length; i++)
    29.   {
    30.   float distance = Mathf.Abs((obj.position - points[index].position).magnitude);
    31.  
    32.   if (distance > 0.001F)
    33.   {
    34.   if (index != 0)
    35.   obj.position = Vector3.MoveTowards(obj.position, points[index].position, 0.3F * Time.deltaTime);
    36.   else
    37.   obj.position = points[index].position;
    38.   }
    39.   else
    40.   index++;
    41.  
    42.   if (index == points.Length)
    43.   index = 0;
    44.   }
    45.  
    46.   }
    47. }
    48.  
    This works but only for 1 object...
     
    Last edited: May 28, 2015
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Have each object move itself. You've already pretty much figured out how to get an object to follow a set of waypoints. So, write a script that moves just "this" object along a set of waypoints. Then put that script on each object you want to move (possibly starting at a different point in the waypoints array, if needed).

    This is way easier, and for many reasons better, than trying to have one master controller script that moves a bunch of objects.
     
  4. nbg_yalta

    nbg_yalta

    Joined:
    Oct 3, 2012
    Posts:
    378
    I thought about it, but this way dosen't suit my needs... Anyway I've already done it with a class with positions and index for each object.