我正在生成许多具有随机位置的圆圈。我要防止的是圆圈相互重叠。所以我想将新生成的 CGPoint 值与数组中的值进行比较,如果该值位于其中一个 CGPoint 的半径区域中,则让它生成一个新值。
除了重叠的东西,我得到了大部分。我已经从我尝试过的东西中评论了这部分,但这并没有真正起作用(有缺陷的逻辑)。我不确定如何遍历 CGPoint 的各个值并进行比较。
更新: 我对代码进行了一些更改,并添加了一个检查以查看 CGPoint 是否会重叠。问题是每当我想尝试类似的东西时
while (!xPointOk || !yPointOk) {
// generate new values
}
我不断陷入无限循环。
- (void) positionCircles
{
//generate random Y value within a range
int fromNumberY = 500;
int toNumberY = 950;
int randomNumberY =(arc4random()%(toNumberY-fromNumberY+1))+fromNumberY;
//generate random Y value within a range
int fromNumberX = 0;
int toNumberX = 700;
int randomNumberX = (arc4random()%(toNumberX-fromNumberX+1))+fromNumberX;
//array to hold all the the CGPoints
positionsArray = [[NSMutableArray alloc] init];
CGPoint circlePositionValue;
CGFloat radius = 70;
CGRect position = CGRectMake(randomNumberX,randomNumberY, radius, radius);
[self makeColors];
// create a circle for each color in color array
for (int i = 0; i < [colors count];i++)
{
// generate new position before placing new cirlce
randomNumberX = (arc4random()%(toNumberX-fromNumberX+1))+fromNumberX;
randomNumberY = (arc4random()%(toNumberY-fromNumberY+1))+fromNumberY;
circlePositionValue = CGPointMake(position.origin.x, position.origin.y);
for (NSValue *value in positionsArray) {
BOOL xPointOk = (randomNumberX < value.CGPointValue.x - radius) ||
(randomNumberX > value.CGPointValue.x + radius);
BOOL yPointOk = (randomNumberY < value.CGPointValue.y - radius) ||
(randomNumberY > value.CGPointValue.y + radius);
NSLog(@"xPoint: %i - %f", randomNumberX , value.CGPointValue.x);
NSLog(@"xPoint ok? %@", xPointOk?@"yes":@"no");
NSLog(@"yPoint: %i - %f", randomNumberY , value.CGPointValue.y);
NSLog(@"yPoint ok? %@", yPointOk?@"yes":@"no");
NSLog(@"___");
}
position.origin.x = randomNumberX;
position.origin.y = randomNumberY;
[positionsArray addObject:[NSValue valueWithCGPoint:circlePositionValue]];
Circle *myCircle = [[Circle alloc] initWithFrame:position radius:radius color:[colors objectAtIndex:i]];
myCircle.label.text = [NSString stringWithFormat:@"%i", i];
[self.view addSubview:myCircle];
}
}