我很好奇今天遇到的一种情况,当我尝试将SKSpriteNode从一个SKScene解压缩并复制到另一个SKScene时.在下面的游乐场的输出中你可以看到在复制之后还是没有维护linearDamping和angularDamping(它们似乎都回退到默认值)
// 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
游乐场输出
我不确定我是否正确地复制了这个,SKSpriteNode和SKPhysicsBody都符合NSCopying如果你看一下上面的输出,就会在复制之后保留area属性,据我所知,这是基于创建SKPhysicsBody时指定的大小.
任何人都可以对此有所了解并且可能会向我提供一个关于我应该如何深度复制SKSpriteNode的指针?
我采取一种方法来解决你的问题,可能不是最好的方法,但是
原文链接:https://www.f2er.com/swift/318617.html//COPY let spriteCopy = spriteNode.copy() as SKSpriteNode let physicsCopy:SKPhysicsBody = spriteNode.physicsBody!; ... //COPY PHYSICS BODY HARD MODE spriteCopy.physicsBody = physicsCopy;
为了解决这个问题,我创建了一个扩展,@ mogelbuster建议覆盖默认的copy(),蚂蚁听起来很棒.
extension SKSpriteNode { override open func copy() -> Any { let node = super.copy() as! SKSpriteNode; node.physicsBody = super.physicsBody; return node; } }
使用此扩展,您可以执行此操作,默认的copy()方法返回Any,因为您需要强制转换为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