2

I'm having a little bit of trouble with one of my projects in Swift at the moment. I want to know if you can create a brand new sprite node like this:

var spriteNode : SKSpriteNode = nodes(3)

where nodes is an array of SKSpriteNodes and has an object at index number 3. Previously, I have worked in Java, and I know that if you were to do something like this, it would simply pass a reference the sprite node variable rather than creating a whole new sprite node, but I am not sure if this is what happens in swift.

If you cannot create a new sprite node this way, what is the best way to make it (In Java you would simply create a new sprite node and literally copy all of its values)?

Jake
  • 73
  • 2
  • 6
  • You want to __clone__ a sprite from an existing one? Any reason why? – Luca Angeletti Aug 13 '16 at 00:20
  • Yes - at the moment, I have an array of three different types of sprites, and I want to generate an array containing 20+ of these sprites in a random order. I don't know if this is the right way to go about this, but I want to clone the sprite in the original array before adding it to the larger array – Jake Aug 13 '16 at 00:23

1 Answers1

1

You can clone an SKSpriteNode using this code

let sprite0 = SKSpriteNode()
let sprite1 = sprite0.copy() as! SKSpriteNode

If you have an array of sprites

let sprites: [SKSpriteNode] = [SKSpriteNode(), SKSpriteNode(), SKSpriteNode()]

you can access a value using the square brackets

let aSprite = sprites[0]

Anyway before using patterns/techniques of other environments I really suggest you to read the Sprite Kit Programming Guide. Often things get easier if we use a tool the way it is intended to be.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • @Jake: Please read [this](http://stackoverflow.com/help/someone-answers) – Luca Angeletti Aug 13 '16 at 00:33
  • If i recall correctly, when using copy() method, sprite's physics body is not copied as it should. Some properties will not have the same value as original. I think there is a post about this on SO already, so be careful when copying sprites like this. – Whirlwind Aug 13 '16 at 06:28
  • @Whirlwind: thanks, maybe this [one](http://stackoverflow.com/questions/28740031/how-to-copy-skspritenode-with-skphysicsbody)? – Luca Angeletti Aug 13 '16 at 12:07
  • That's the one. I haven't tested this lately, but it probably works the same as then. – Whirlwind Aug 13 '16 at 12:10