简体   繁体   中英

how to randomly add sprites to scene

Im trying to add multiple images to my scene randomly. I have 4 images named Gem1, Gem2, Gem3, and Gem4. I'm stuck. Here's the code i have so far but there are errors. Can someone help me please?

- (void)addGem {

// Create sprite
NSString *base = @"Gem";
uint32_t num = arc4random_uniform(4) + 1; //Generate a random number
NSString *GemName = [base stringByAppendingFormat:@"%d.png", num];
SKSpriteNode * Gem = [SKSpriteNode spriteNodeWithImageNamed:@"GemName"];

_gem = Gem;

Gem.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:Gem.size]; // 1
Gem.physicsBody.dynamic = YES; // 2
Gem.physicsBody.categoryBitMask = GemCategory; // 3
Gem.physicsBody.contactTestBitMask = monsterCategory; // 4
Gem.physicsBody.collisionBitMask = 0;

int minx = 200;
int maxx = 1000;
int rangex = maxx - minx;
int actualx = (arc4random() % rangex) + minx;
int minY = 900;
int maxY = 1200;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;

Gem.position = CGPointMake(actualx, actualY);

[_background addChild:Gem];
[self runAction:[SKAction sequence:@[
[SKAction waitForDuration:5],
[SKAction performSelector:@selector(addGem) onTarget:self],]]];


}

Just remove the "". :D

From

SKSpriteNode * Gem = [SKSpriteNode spriteNodeWithImageNamed:@"GemName"];

To

SKSpriteNode * Gem = [SKSpriteNode spriteNodeWithImageNamed:GemName];

Need you to post the "addGem" method to help you with the position issue; if you are having any.

SKSpriteNode * Gem = [SKSpriteNode spriteNodeWithImageNamed:@"GemName"];

这里GemName是一个变量,不应将其用""包裹,只需将其删除即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM