cmii
cmii

Reputation: 3636

How to duplicate a sprite with physics properties then add it to the scene?

I have a sprite in my scene editor, called "redsprite" with some physics properties. I really want to use this sprite for the next.

I would like to "duplicate" this sprite, keeping his physics properties, but with a new position.

let sprite:SKSpriteNode = (self.childNode(withName: "redsprite") as! SKSpriteNode).copyWithPhysicsBody()
sprite.position = CGPoint(x:100,y:100)
self.addChild(sprite)

I use an SKSpriteNode extension to copy the sprite.

extension SKSpriteNode  {
    func copyWithPhysicsBody()->SKSpriteNode {
       let node = self.copy() as! SKSpriteNode
       node.physicsBody = self.physicsBody
       return node
    }
}

I have this classical error:

Terminating app due to uncaught exception 'Cant add body, already exists in a world', reason: 'Cant add body <SKPhysicsBody> type:<Rectangle> representedObject:[<SKSpriteNode> name:'redsprite' texture:['nil'] position:{100, 100} scale:{1.49, 1.40} size:{149.15391540527344, 140.06228637695312} anchor:{0.5, 0.5} rotation:0.00], already exists in a world'

I understood the error, it's very clear, but I don't find a way to avoid it.

Upvotes: 1

Views: 193

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

You are taking the original body and putting it on 2 nodes. You cant do that.

As far as I remember, physicsBody now gets copied in the copy command (it didn't always). So you should not need to transfer the original body over. If it doesn't copy, then do:

node.physicsBody = self.physicsBody.copy()

Upvotes: 3

Related Questions