Sprite Kit - 使用Switch Case向场景添加随机Sprite节点
问题描述:
我有以下代码来创建随机对象并将它们添加到场景中。最后,在随机延迟后重复该方法。Sprite Kit - 使用Switch Case向场景添加随机Sprite节点
-(void)createObjects {
// Create random start point
float randomStartPoint = arc4random_uniform(4) * 64 + 32;
CGPoint startPoint = CGPointMake(self.size.width + 50, randomStartPoint);
// Create random object and add to scene
switch (arc4random_uniform(2)) {
case 0:
{
SKSpriteNode *crate = [SKSpriteNode spriteNodeWithImageNamed: @"crate"];
crate.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:crate.frame.size];
crate.physicsBody.dynamic = YES;
crate.physicsBody.affectedByGravity = NO;
crate.physicsBody.categoryBitMask = objectCategory;
crate.physicsBody.collisionBitMask = 0;
crate.physicsBody.contactTestBitMask = playerCategory;
crate.position = startPoint;
crate.name = @"object";
crate.zPosition = 20;
[self addChild:crate];
break;
}
case 1:
{
SKSpriteNode *cactus = [SKSpriteNode spriteNodeWithImageNamed: @"cactus"];
cactus.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:cactus.frame.size];
cactus.physicsBody.dynamic = YES;
cactus.physicsBody.affectedByGravity = NO;
cactus.physicsBody.categoryBitMask = objectCategory;
cactus.physicsBody.collisionBitMask = 0;
cactus.physicsBody.contactTestBitMask = playerCategory;
cactus.position = startPoint;
cactus.name = @"object";
cactus.zPosition = 20;
[self addChild:cactus];
break;
}
default:
break;
}
// After adding child, call same method at random delay
float randomNum = arc4random_uniform(4) * 0.4 + 0.25;
[self performSelector:@selector(createObjects) withObject:nil afterDelay:randomNum];
}
在现实中,我还有更多的情况下,重复很多相同的代码,因为每个节点雪碧具有相同的设置。有没有办法一次创建一个精灵节点,并且在每种情况下都为节点设置一个不同的图像,并将其添加到场景中?
答
您可以在switch case中创建SKTexture,然后使用该纹理创建节点。
像这样:
-(void)createObjects {
// Create random start point
float randomStartPoint = arc4random_uniform(4) * 64 + 32;
CGPoint startPoint = CGPointMake(self.size.width + 50, randomStartPoint);
// Create random object and add to scene
SKTexture* objectTexture;
switch (arc4random_uniform(2)) {
case 0:
objectTexture = [SKTexture textureWithImageNamed:@"crate"];
break;
case 1:
objectTexture = [SKTexture textureWithImageNamed:@"cactus"];
break;
default:
break;
}
SKSpriteNode *object = [SKSpriteNode spriteNodeWithTexture:objectTexture];
object.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:crate.frame.size];
object.physicsBody.dynamic = YES;
object.physicsBody.affectedByGravity = NO;
object.physicsBody.categoryBitMask = objectCategory;
object.physicsBody.collisionBitMask = 0;
object.physicsBody.contactTestBitMask = playerCategory;
object.position = startPoint;
object.name = @"object";
object.zPosition = 20;
[self addChild: object];
}
另一种方式是之前切换的情况下创建对象,然后简单地创建质感和使用的SetTexture设置在开关的情况下:
伟大的作品!非常感谢! – user2255273
嗨,当我按照这个在迅速崩溃说致命的错误 - 意外地发现零,而解包可选值 – anjani
@ user2255273你从哪个方法调用[自createObjects]? – user3404693