How to copy SKSpriteNode using SKPhysicsBody?

I am interested in the situation that I encountered today when trying to parse and copy SKSpriteNode from one SKScene to another. At the exit from the playground below, you can see that both linearDamping and angularDamping either not supported after copying (they seem to return to their default values)

 // PLAYGROUND_SW1.2 - SKSpriteNode Copy import UIKit import SpriteKit // ORIGINAL let spriteNode = SKSpriteNode() spriteNode.name = "HAPPY_NODE" let size = CGSize(width: 55.0, height: 150.0) let physics = SKPhysicsBody(rectangleOfSize: size) physics.linearDamping = 0.123 physics.angularDamping = 0.456 spriteNode.physicsBody = physics // COPY let spriteCopy = spriteNode.copy() as! SKSpriteNode // ORIGINAL spriteNode.name spriteNode.physicsBody?.linearDamping spriteNode.physicsBody?.angularDamping spriteNode.physicsBody?.area // COPY spriteCopy.name spriteCopy.physicsBody?.linearDamping spriteCopy.physicsBody?.angularDamping spriteCopy.physicsBody?.area 

PLANNED OUTPUT enter image description here

I'm not sure if I am copying this correctly, and SKSpriteNode and SKPhysicsBody compliant. If you look at the result above, the area property is saved after the copy, and as far as I know, this is based on the size specified when creating SKPhysicsBody .

Can someone highlight this and perhaps provide me with a pointer to how I should deep copy SKSpriteNode ?

+6
source share
1 answer

I am doing one way to solve your problem, maybe this is not the best way, but

  //COPY let spriteCopy = spriteNode.copy() as SKSpriteNode let physicsCopy:SKPhysicsBody = spriteNode.physicsBody!; ... //COPY PHYSICS BODY HARD MODE spriteCopy.physicsBody = physicsCopy; 

To fix this problem, I created one extension, and @mogelbuster suggested overriding the default copy() , ant, that sounds great.

 extension SKSpriteNode { override open func copy() -> Any { let node = super.copy() as! SKSpriteNode; node.physicsBody = super.physicsBody; return node; } } 

With this extension you can do this, the copy() method returns Any by default because you need to do it on SKSpriteNode .

 // COPY let spriteCopy = spriteNode.copy() as! SKSpriteNode; // ORIGINAL spriteNode.name spriteNode.physicsBody?.linearDamping spriteNode.physicsBody?.angularDamping spriteNode.physicsBody?.area // COPY spriteCopy.name spriteCopy.physicsBody?.linearDamping spriteCopy.physicsBody?.angularDamping spriteCopy.physicsBody?.area 

IMAGE

+10
source

Source: https://habr.com/ru/post/983036/


All Articles