Game Development Community

Picking a random point in a given radius?

by Teck Lee Tan · in Torque Game Builder · 09/18/2005 (11:33 am) · 2 replies

Okay, so may be a really stupid question brought on by my physically-exhausted and sleep-deprived state, but I can't think of a decent solution to it.

So, how, given a pair of world coords, would I go about returning world coords of a completely random (ie, unbiased) point within a set radius? I realize that it would be a simple solution if I wanted to get random points in a rectangle/square, but a circle?

edit:
Okay, so it's kinda funny how you get random solutions in your head right after asking. Although, to be fair, the solution that popped into my head is pretty ugly. Okay, reallyugly.

pseudocode:
get coord
angle = getRandom(360)
distance = getRandom(radius)
then do some vector ops to get the world coord of point (distance) from center at (angle) degrees
or do some basic geometry to get x and y components, and add those to the original coords

Any cleaner solutions?

#1
09/18/2005 (1:40 pm)
Relatively simple, though if anyone has anything even more efficient that would be lovely.

function getRandomPoint(%coord, %radius)		//returns paired coord, random point in defined radius
{
	%angle = getRandom(360);
	%radius = getRandom(%radius);
	%lenX = (mCos(%angle) * %radius);		//rise
	%lenY = (mSin(%angle) * %radius);		//run
	%target = vectorAdd2D(%coord, %lenX SPC %lenY);
	echo(%coord SPC %lenX SPC %lenY SPC %target);
	return(%target);
}
#2
09/18/2005 (2:08 pm)
Wouldn't say this is simpler, but it seems to work:

function getRandomPointInRadius(%startPointX, %startPointY, %maxRadius)
{
    %dist = getRandom() * %maxRadius;
    %randomVector = ((getRandom() * 2) - 1) SPC ((getRandom() * 2) - 1);
    %normalRandomVector = vectorNormalise2D(%randomVector);
    %scaledVector = vectorScale2D(%normalRandomVector, %dist);
    %endPointX = %startPointX + getWords(%scaledVector,0,1);
    %endPointY = %startPointY + getWords(%scaledVector,1,1);

    %endPoint = %endPointX SPC %endPointY;
    echo ("EndPoint: " SPC %endPoint);
}