Duplicate Sprite in Random Positions with SpriteKit

北战南征 提交于 2019-12-25 07:16:37

问题


I'm trying to create a game with Swift and SpriteKit and I'd like to create multiple instances of the same sprite in random positions, but I can't figure out how to do it. I considered just doing adding this code: addChild(object) multiple times, but this causes the app to crash. How can I solve my problem?

EDIT: I've fixed this part of the problem, but now I want to add my random sprites in random X locations. I've tried to generate random positions by executing this code: var randomNumber = arc4random_uniform(8) crateDuplicate.position = (CGPointMake(randomNumber, 200)) But, I get an error of "Cannot assign a value of type '(CGPoint)' to a value of type 'CGPoint'." What should I do?


回答1:


Do this:

let randomNumber = CGFloat(arc4random_uniform(8))
position = CGPointMake(randomNumber, 200)

arc4random_uniform returns an UInt32 and you need a CGFloat, so you need to convert it. Also skip the () around CGPointMake otherwise you'll create a tuple.

For more ways of getting random numbers and other useful stuff, have a look at this collection of utility classes and functions by the Ray Wenderlich team: https://github.com/raywenderlich/SKTUtils



来源:https://stackoverflow.com/questions/31105061/duplicate-sprite-in-random-positions-with-spritekit

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