[英]How can I evenly scatter points without overlapping each other?
I'd like to evenly scatter stars to represent a night sky background in a UIView, based on the UIView's width and height. 我想基于UIView的宽度和高度,均匀地散射星星来代表UIView中的夜空背景。 Each star must be at least 20 pixels apart. 每颗恒星必须至少相隔20个像素。
I tried the following to generate the X and Y points, but it is highly inefficient and ends up freezing the app because too often the randomly generated numbers are too similar to those in the existing array, causing it to loop again infinitely. 我尝试了以下方法来生成X和Y点,但效率非常低并最终冻结了应用程序,因为随机生成的数字太频繁地与现有数组中的数字太相似,导致它无限循环。
func generateRandomNumber(maxValue: UInt32, uniquePoints: Set<Int>) -> Int {
let randomNumber = Int(arc4random_uniform(maxValue))
for point in uniquePoints {
if(abs(randomNumber - point) < 20) {
return generateRandomNumber(maxValue, uniquePoints)
}
}
return randomNumber
}
Is there a more efficient way to do this? 有没有更有效的方法来做到这一点?
The easiest way, if they need to be 20 pixels apart is to divide your area into 20 x 20 squares. 最简单的方法是,如果它们需要相隔20个像素,则将您的区域划分为20 x 20格。 Randomly place 1 star in each 20 x 20 cell, but skip every other column and row. 在每个20 x 20单元格中随机放置1颗星,但跳过每隔一列和每行。 So it would look like this: 所以它看起来像这样:
*-*-*-*-*
|-|-|-|-|
*-*-*-*-*
|-|-|-|-|
etc. In the above illustration, cells with a *
in them would have a single star. 在上图中,其中带有*
单元格将具有单个星形。 Cells with either a -
or a |
与无论是细胞-
还是|
would be empty. 会是空的。
If you want to get more complicated, you can look up Poisson Disc . 如果你想变得更复杂,你可以查找Poisson Disc 。 This is a more complicated method that achieves what you want more elegantly. 这是一种更复杂的方法,可以更优雅地实现您想要的效果。 It's a little harder to understand, though, and can often be computationally intensive. 但是,它有点难以理解,并且通常可能是计算密集型的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.