将新的CGPoint值与数组中的CGPoint值进行比较
问题描述:
我正在生成具有随机位置的多个圆圈。我想要阻止的是圈子彼此重叠。所以我想将新生成的CGPoint值与数组中的值进行比较,如果该值发现自己位于其中一个CGPoint的半径区域中,则会生成一个新值。将新的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? %@", [email protected]"yes":@"no");
NSLog(@"yPoint: %i - %f", randomNumberY , value.CGPointValue.y);
NSLog(@"yPoint ok? %@", [email protected]"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];
}
}
答
当新点小于任何现有点的圆周时,您的测试应该失败,因此您可以使用基本的三角函数来解决问题。
BOOL far_enough_away = NO;
CGPoint newpoint = CGZeroPoint;
while(!far_enough_away)
{
newpoint = randomisation_thingy();
far_enough_away = YES;
for(NSValue *existing in positionsArray)
{
CGPoint pointb = [existing pointValue];
CGFloat deltay = pointb.y-newpoint.y;
CGFloat deltax = pointb.x-newpoint.x;
CGFloat distance = sqrt(pow(deltax,2) + pow(deltay,2));
//fail if closer than desired radius
if(distance < circumference)
{
//sadness - try again
far_enough_away = NO;
break;
}
}
}
create_a_new_circle_at_point(newpoint);
其他事情你需要考虑的是要重试多少次来停止无限次的重试。
你好,我尝试将你的代码合并到我的。但我似乎没有得到它的工作。虽然我明白你的方式肯定是更有效率的。我能否在不使用trig的情况下工作? – 2012-04-08 15:13:36
这是伪代码。不要复制/粘贴。适应你在那里看到的节目。不,你需要使用基本的三角函数来解决这个问题。 – 2012-04-08 17:31:03
是的我现在工作。谢谢!虽然我需要学习一些基本的触发:) – 2012-04-08 20:10:56