我正在使用SpriteKit创建一个游戏,在这个游戏中,地图底部的对象移动。这些物品是鳄鱼和硬币。
场景使用一个NSTimer来调用这个选择器:
timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(generateBottomSprite) userInfo:nil repeats:YES];
-(void) generateBottomSprite{
int random = (arc4random() % difficulty+3) + difficulty-3;
if (counter >random){
SKSpriteNode *bottomSprite;
if (random>difficulty){
bottomSprite = [SKSpriteNode spriteNodeWithImageNamed:@"crocodile"];
bottomSprite.size = CGSizeMake(70, 120);
bottomSprite.physicsBody.categoryBitMask = crocMask;
}else{
bottomSprite = [SKSpriteNode spriteNodeWithImageNamed:@"coin"];
bottomSprite.size = CGSizeMake(50, 50);
bottomSprite.physicsBody.categoryBitMask = coinMask;
}
//create a crocodile
bottomSprite.position = CGPointMake(self.frame.size.width,bottomSprite.frame.size.height/2);
bottomSprite.name = @"bottomSprite";
[self addChild: bottomSprite];
counter = 0;
[self enumerateChildNodesWithName:@"bottomSprite" usingBlock: ^(SKNode *node, BOOL *stop) {
node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node.frame.size];
node.physicsBody.affectedByGravity = NO;
node.physicsBody.mass = 8000.0;
node.physicsBody.friction = 2.50;
node.physicsBody.usesPreciseCollisionDetection = YES;
}];
}}
问题是:在每次调用选择器时,都会重新初始化physicsWorld的所有属性,为了重新分配它们,我必须遍历场景的子元素。
为什么要重新初始化属性?
发布于 2014-03-23 15:46:09
在创建skphysicsbody本身之前,您正在设置分类位掩码。
bottomSprite = [SKSpriteNode spriteNodeWithImageNamed:@"crocodile"];
bottomSprite.size = CGSizeMake(70, 120);
//add the following
bottomSprite.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:bottomSprite.frame.size];
///////////////
bottomSprite.physicsBody.categoryBitMask = crocMask;将所有物理设置移出枚举,如下所示
if (counter >random){
SKSpriteNode *bottomSprite;
int currentBitMask;
if (random>difficulty){
bottomSprite = [SKSpriteNode spriteNodeWithImageNamed:@"crocodile"];
bottomSprite.size = CGSizeMake(70, 120);
currentBitMask = crocMask;
}else{
bottomSprite = [SKSpriteNode spriteNodeWithImageNamed:@"coin"];
bottomSprite.size = CGSizeMake(50, 50);
currentBitMask = coinMask;
}
**bottomSprite.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:bottomSprite.frame.size];**
bottomSprite.physicsBody.categoryBitMask = currentBitMask ;
bottomSprite.physicsBody.affectedByGravity = NO;
bottomSprite.physicsBody.mass = 8000.0;//way too high
bottomSprite.physicsBody.friction = 2.50;//probably high
bottomSprite.physicsBody.usesPreciseCollisionDetection = YES;//overkill, set only if critical
//create a crocodile
bottomSprite.position = CGPointMake(self.frame.size.width,bottomSprite.frame.size.height/2);
bottomSprite.name = @"bottomSprite";
[self addChild: bottomSprite];您还可能想要使用最新场景中的update方法和NSTimer来测量时间,直到超过半秒钟,然后调用generateBottomSprite方法,它应该比使用额外的NSTimer更有效。
如果有什么不清楚的地方,请随便问,希望这会有所帮助。
https://stackoverflow.com/questions/22584110
复制相似问题