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?
Here is a video which demonstrates the behavior I am looking for.
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.