# Random position inside multiple areas

Hi,

I got an object following a Waypoint in 3d space. Every time the player collides with the waypoint, the waypoint moves(teleports) to another location within given range. This is the script im using for the waypoint;

function OnTriggerEnter (myTrigger : Collider) {

`````` if(myTrigger.gameObject.name == "Sphere"){
this.transform.position = Vector3(Random.Range(-80, 100), Random.Range(5, 10), Random.Range(-80, 100));
}
}
``````

This works fine but i would like to limit the randomness within two different areas. (See image - pink dot is wayponit).
If the waypoint is inside Area#1 when it collides with the object it will move to a random position inside Area#2. Then, when it collides with the object inside Area#2 it will move to a random position inside Area#1 and so on.

I would be most grateful for any ideas, help, advice on this!

/Fredrik

This should be pretty easy

Take and make 2(or infinite) empty game objects which define the (0,0,0) point of a possible AREA.

This allows you to move within a range but to have that range start at that point. Your going to move in the local space of that object (that object will be the center of the universe basically)

To simplify things for later you should probably take and gather all these objects up and make a list of gameobjects

first we’ll pick a random area to go to EXCEPT we wont go to the same area we are
currently in. You can ignore this step if you want to go in a sequential order.
from area 1 to 2 and so on. In that case just iterate through the list instead of picking
a random one.

``````bool FoundNewArea = false;

gameobject Area;
int iterator;
int randomIterator;
while(!FoundNewArea)
{
RandomIterator = random.range(0,ListOfGameobjects.size -1);
//this next line makes sure we didnt pick to go to where we already are,
//again you can remove this if you want a CHANCE you pick the area your already in
if(iterator != RandomIterator)
{
iterator = randomiterator
FoundNewArea = true;
}
}

transform.position = ListOfGameObjects[iterator].transform.position + randomVector;
``````

Of course now each area would be uniform in size you could fix that too but this code would do what you want which is to take whatever area your in.
Find a new area out of a list of possible ones.
And move to a random location int aht area.