Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Random Range Problem?

Discussion in 'Scripting' started by Cooper37, Mar 4, 2016.

  1. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    Hi all! I'm using Random.Range for my waypoint system, but I'm having a bit of a detail issue. The following line of code does give me a random position, but only around Vector3.zero, bounded to the radius(center of space as I call it). How can I alter this bit of code to where it gives me a random position around the object this script is attached to?
    Thanks :)

    js.
    Code (csharp):
    1.  
    2. function ChangeWaypoint(){
    3.     waypoint.transform.position = Vector3(Random.Range(-radius, radius), 0.0, Random.Range(-radius, radius));
    4. }
    5.  
     
  2. ericbegue

    ericbegue

    Joined:
    May 31, 2013
    Posts:
    1,353
    You just have to add your object position.
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Code (csharp):
    1. function ChangeWaypoint(){
    2.     waypoint.transform.position = Vector3(Random.Range(-radius, radius), 0.0, Random.Range(-radius, radius)) + transform.position;
    3. }
     
  4. ericbegue

    ericbegue

    Joined:
    May 31, 2013
    Posts:
    1,353
    Just a remark:
    You are using the word "radius", which suggests that the position is on a disk.
    But the generated position is inside a square.
     
    Kiwasi and LeftyRighty like this.
  5. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    Thanks guys,
    Um, I don't think so...I'm using radius for visualization. I drew a wire sphere around my gameObject and set it to the radius. I just really wanted the waypoint to stay within that sphere. It seems to be working now. Thanks, guys! :)
     
  6. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
  7. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    just work the math, if radius is 1, you get points from (-1, -1) through (-1, 1), (1, -1) to (1, 1). That's the corner limits of a square (~1.2 distance from the centre (0, 0)), not a circle...
     
    Kiwasi and ericbegue like this.
  8. Cooper37

    Cooper37

    Joined:
    Jul 21, 2012
    Posts:
    383
    I was considering using this, but I was much more familiar using Random.Range. I might convert over...

    Huh. I see...
     
  9. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    For many game effects this is 'good enough' it's certainly easier to build.

    But it's worth being aware of exactly what you are doing.