I know that there are many collision detection messages, usually for sprites moving around a 2D plane, but my question is slightly different.
I insert circles into a 2D plane. Circles have variable radii. I am trying to optimize my method of finding a random position in a plane, where I can insert a new circle without interfering with other circles already on the plane. Now I use a very “not optimized” approach, which simply generates a random point inside the plane and then checks it on all other circles on the plane.
Are there any ways to optimize this? For this particular application, the borders of the plane can hold only 20-25 circles at a time, and usually they are from 5 to 10. As you would expect, when the number of circles approaches the maximum that can fit, you need to check a lot of points before finding one that works. This is very slow.
Note: safeDistance is the radius of the circle that I want to add to the plane.
Here is the code:
- (CGPoint)getSafePosition:(float)safeDistance {
CGPoint thePoint;
BOOL pointIsSafe = NO;
int sd = ceil(safeDistance);
while(!pointIsSafe) {
self.pointsTested++;
thePoint = CGPointMake((arc4random() % ((int)self.manager.gameView.frame.size.width - sd*2)) + sd,
(arc4random() % ((int)self.manager.gameView.frame.size.height - sd*2)) + sd);
if(self.manager.gameView.sprites.count > 0) {
for(BasicSprite *theSprite in self.manager.gameView.sprites) {
float distance = [BasicSprite distanceBetweenPoints:thePoint b:theSprite.position];
if(distance < (safeDistance + [theSprite minSafeDistance])) {
pointIsSafe = NO;
break;
}
pointIsSafe = YES;
}
}
else {
pointIsSafe = YES;
}
}
return thePoint;
}
Steve
source
share