1
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ 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 \$\endgroup\$
    – RJV
    Commented Jul 23, 2015 at 11:53
  • \$\begingroup\$ 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. \$\endgroup\$
    – Philipp
    Commented Jul 23, 2015 at 12:08
  • \$\begingroup\$ What is the timestamp in the video that you want us to look at? \$\endgroup\$
    – Evorlor
    Commented Jul 23, 2015 at 13:24
  • 1
    \$\begingroup\$ @Evorlor Timestamp is 1.15 \$\endgroup\$
    – RJV
    Commented Jul 23, 2015 at 13:36

1 Answer 1

1
\$\begingroup\$

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.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .