Random Range Problem?

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 :slight_smile:

js.

function ChangeWaypoint(){
    waypoint.transform.position = Vector3(Random.Range(-radius, radius), 0.0, Random.Range(-radius, radius));
}

You just have to add your object position.

function ChangeWaypoint(){
    waypoint.transform.position = Vector3(Random.Range(-radius, radius), 0.0, Random.Range(-radius, radius)) + transform.position;
}

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.

2 Likes

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! :slight_smile:

there are other “randoms”

for example

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…

2 Likes

I was considering using this, but I was much more familiar using Random.Range. I might convert over…

Huh. I see…

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.