# Random movement of game Object staying in a circle

I want to write a script which makes several objects move in a random direction but within a range around another game object. If the parent object moves then that range should also be changed accordingly.

How can I achieve such behavior?

It looks approximately like this:

   void Update ()
{
time += Time.deltaTime;

if (time > 1.0f)
{
CalculateRandomRotation ();
time = 0f;
}

FindSpiritsBound ();

}

void CalculateRandomRotation()
{
x       = Random.Range(-velocityMax, velocityMax);
z       = Random.Range(-velocityMax, velocityMax);
angulo  = Mathf.Atan2(x, z) * (180 / 3.141592f);
time    = 0.0f;
transform.localRotation = Quaternion.Euler(0, angulo, 0);
}

void FindSpiritsBound()
{
if (Vector3.Distance (parentObj.transform.position, gameObject.transform.position) < 3f)
{
gameObject.transform.localPosition += gameObject.transform.forward * 4f * Time.deltaTime;
}
else
{
transform.position = Vector3.MoveTowards(transform.position, parentObj.transform.position, 2.0f);
}
}


Here is my script which doesn't seem to work properly as on moving the main character, spirits are going wayward.

• A script which makes all the spirits move in a random direction but within a range from the main character. If the character moves then that range should also be changed accordingly – RJV Jul 23 '15 at 11:53
• I rewrote your question to fulfill at least a minimum of quality necessary for a question on this site. Because you are not providing enough information I had to guess a bit. Feel free to make further edits and add more details. The more accurate and specific the description of your problem the more helpful the answers will be. – Philipp Jul 23 '15 at 12:08
• What is the timestamp in the video that you want us to look at? – Evorlor Jul 23 '15 at 13:24
• @Evorlor Timestamp is 1.15 – RJV Jul 23 '15 at 13:36

In the script of the random movement of the sprites check the distance by using the command Vector3.Distance(object a, object b). If the sprite is not in range than move/change direction of the movement.