Spritekit: Separating randomly placed non-dynamic “block” nodes by a set X and Y value?

橙三吉。 提交于 2020-01-05 04:09:11

问题


my script below does exactly what i need it to do, add blocks to a scene in any random order in the view. the only problem is, as i increase the amount of "block" nodes, they tend to overlap on one another and clump up, I'm wondering if there is a way i can add a "barrier" around each block node so that they cannot overlap but still give a random feel? My current code is below:

-(void) addBlocks:(int) count {
for (int i = 0; i< count; i++) {

SKSpriteNode *blocks = [SKSpriteNode spriteNodeWithImageNamed:@"Ball"];
blocks.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:(blocks.size.width/2)];
blocks.physicsBody.dynamic = NO;
blocks.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
[self addChild:blocks];


int blockRandomPositionX = arc4random() % 290;
int blockRandomPositionY = arc4random() % 532;
blockRandomPositionY = blockRandomPositionY + 15;
blockRandomPositionX = blockRandomPositionX + 15;
blocks.position = CGPointMake(blockRandomPositionX, blockRandomPositionY);



}

}

Any help highly appreciated, thanks!


回答1:


To prevent two nodes from overlapping, you should check the newly created node's random position with intersectsNode: to see if it overlaps any other nodes. You also have to add each successfully added node into an array against which you run the intersectsNode: check.

Look at the SKNode Class Reference for detailed information.



来源:https://stackoverflow.com/questions/23654110/spritekit-separating-randomly-placed-non-dynamic-block-nodes-by-a-set-x-and-y

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!