选择多边形线上的随机点
我使用的是 Java Polygon 对象,它存储定义构成形状的线条的点数组。
我将如何在这些线上选择一个随机点? Polygon 类中是否有任何方法可以使这变得更容易?
为了澄清这一点,我想从多边形边缘的任何位置选取一个随机点,而不一定是从定义的顶点集中选取一个点。
I'm using a Java Polygon object, which stores an array of points which define the lines that make up the shape.
How would I go about selecting a random point on one of these lines? Are there any methods in the Polygon class that would make this easier?
To clarify, I want to pick a random point from any position on the edge of the polygon, not necessarily from the set of defined vertices.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您要做的第一件事是找到多边形的周长。
现在找一个0到perimeter范围内的随机数。
然后,迭代多边形的线段,从您的值中减去线段的长度,直到下一条线段的长度比当前值长。
假设您沿着线段“行走的距离”等于您的剩余价值,那么您将在周边上有一个随机点。
==================================
另一个可行的选择是选择一个按其长度偏置的随机段(您可以缓存每个多边形的阈值),然后在随机选取的线段上选取一个随机点。对于大多边形会更快(缓存阈值后的顺序 1),但会经历两倍的随机数。
The first thing you have to do is find the perimeter of the polygon.
Now find a random number the range of 0 to perimiter.
Then, iterate over the segments of the polygon, subtracting the length of the segment from your value until the length of the next segment is longer than your current value.
Pretend you're "walking that distance" along the segment equal to your remaining value, and you'll have a random point on the perimeter.
================================
Another viable option would be to pick a random segment biased by their length (you could cache the thresholds for each polygon) and then pick a random point on the segment that was randomly picked. Would be faster for large polygons (order 1 after you cache the thresholds) but would go through twice the random numbers.
使用点斜率形式为连接顶点的
n
边之一中随机选择的边创建y = mx + b
方程。顶点在Polygon.xpoints
和Polygon.ypoints
中定义。考虑以下因素:
假设我们有一个五边形。我们有 5 个边和 5 个顶点。由于我们在
Polygon
中存储了顶点并且想要一条边,所以我们需要两个顶点来形成一条线,所以我们在0
和5
之间随机选择。假设我们随机生成的数字r = 0
。假设 xpoints[r] = 1、ypoints[r] = 1、xpoints[r+1] = 2 和 ypoints [r+1] = 4。
对于
m
,我们有对于点斜率形式,我们有
现在,在该边的两个 x 边界之间选择一个随机
x
,即在域中[0,2]
,您就得到了随机点(x, y(x))
。Use point-slope form to create a
y = mx + b
equation for a randomly chosen edge out of one of then
edges that connect the vertices. Vertices are defined inPolygon.xpoints
andPolygon.ypoints
.Consider the following:
Suppose we have a pentagon. We have 5 edges and 5 vertices. Since we have vertices stored in
Polygon
and want an edge, we need two vertices to form a line, so we randomly choose between0
and5
. Suppose our randomly generated numberr = 0
.Suppose
xpoints[r] = 1
,ypoints[r] = 1
,xpoints[r+1] = 2
, andypoints[r+1] = 4
.For
m
, we haveFor point-slope form, we have
Now, choose a random
x
between the two x-bounds for this edge, i.e. in the domain[0,2]
, and you have your random points(x, y(x))
.如果数组中有 n 个点,请使用 java Random 类。
If you have n points in the array use the java Random class.