I have point A (pointA = (x1, y1)
) and I need to choose a random point B (pointB = (x2, y2)
) such that the distance between the A and B is equal to K.
Asked
Active
Viewed 719 times
2
-
[This answer][1] has what you're looking for. [1]: http://stackoverflow.com/a/929781/4805137 – David Rans Apr 18 '15 at 17:41
-
possible duplicate of [Calculating the distance between two points](http://stackoverflow.com/questions/929773/calculating-the-distance-between-two-points) – gioele Apr 18 '15 at 17:43
-
That's not a duplicate of this. – Anubian Noob Apr 18 '15 at 17:44
-
3I'm voting to close this question as off-topic because it is a geometry problem, not a coding/software problem. – Brett Okken Apr 18 '15 at 18:53
1 Answers
8
Let's solve in polar form.
We'll need these doubles distance
, x1
, and y1
.
First, we want the angle in radians:
double angle = Math.random()*2*Math.PI;
Then we want to get the x and y offsets from our point:
double xOff = Math.cos(angle)*distance;
double yOff = Math.sin(angle)*distance;
Then we add these to our first point:
double x2 = x1 + xOff;
double y2 = y1 + yOff;
This will get you a point a certain distance
away from your first point.

Anubian Noob
- 13,426
- 6
- 53
- 75