简体   繁体   English

如何将精灵随机添加到场景

[英]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. 我有4个名为Gem1,Gem2,Gem3和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 :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; 需要您发布“ addGem”方法来帮助您解决职位问题; if you are having any. 如果有的话。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过Swift和SpriteKit使视图可滚动以查看带有sprite的整个场景? - How to make a view scrollable to view the full scene with sprites with Swift and SpriteKit? 随机分布精灵 - randomly distribute sprites 在场景中添加两个自定义精灵,为什么这些精灵的方法会互相影响,谁能在我的代码中发现错误? 谢谢 - add two custom sprites into a scene,why do these sprites' methods will effect each other,anyone can find the mistake in my code? thanks 随机给精灵着色,但需要限制 - Randomly coloring sprites, but needs restrictions 如何使用gameplaykit在编辑器中向精灵添加组件 - How to add components to sprites within editor with gameplaykit 如何在场景中添加按钮和标签 - How to add button and label to the scene Sprite Kit:如何在运行场景的顶部添加场景 - Sprite Kit: How to add scene on top of running scene 如何以编程方式将带有zPosition的子级添加到使用场景编辑器创建的场景中 - How to programmatically add child with zPosition to scene created with Scene Editor 在cocos2d-x v3中绘制和添加大量精灵(〜200)的最佳方法是什么? - What is the most optimal way to draw and add to a scene a large number of sprites(~200) in cocos2d-x v3? 在X轴上随机生成精灵 - Spawning sprites randomly on x-axis
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM