0

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?

kriskendall99
  • 547
  • 1
  • 4
  • 14
  • If you want better results here, please post some code of what you have tried. You wil find people will respond better and might be able to help you. – the_pantless_coder Jun 28 '15 at 21:49
  • 1
    Use arc4random to pick x,y positions at random. http://stackoverflow.com/questions/24132399/how-does-one-make-random-number-between-range-for-arc4random-uniform Then add each node instance. – sangony Jun 28 '15 at 21:58
  • How do I add an instance? – kriskendall99 Jun 28 '15 at 22:35
  • @kriskendalll99 You can create copies of same sprite by using copy() method. http://stackoverflow.com/a/30848951/3402095 – Whirlwind Jun 28 '15 at 22:54
  • Thanks for the answer! That worked! However, I'm having a problem assigning my sprite to a random position. I'm getting the error: "Cannot assign a value of type '(CGPoint)' to a value of type 'CGPoint'." Here's my code: `var randomNumber = arc4random_uniform(8) crateDuplicate.position = (CGPointMake(randomNumber, 200))` What am I doing wrong? – kriskendall99 Jun 28 '15 at 23:54
  • @kriskendall99 I can't produce what you are saying. Please update your question (not paste the code in the comments because its not readable like that) with full code which can produce described error. – Whirlwind Jun 29 '15 at 08:51

1 Answers1

0

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

Pontus Armini
  • 348
  • 4
  • 10