SpriteKit构建绳索功能不起作用

时间:2017-04-15 15:16:22

标签: swift sprite-kit skphysicsbody skphysicsjoint

这是我的代码:

 var red: SKSpriteNode?
var redHolding = false
/////
// MARK: didMove
/////
override func didMove(to view: SKView) {
    physicsWorld.contactDelegate = self

    if let r = self.childNode(withName: "red") as? SKSpriteNode { red = r }
    createRope(red!, 10)

}//

func createRope(_ anchorSprite: SKSpriteNode, _ numOfLinks: Int) {
    var links: [SKSpriteNode] = []
    anchorSprite.position = CGPoint(x: 0, y: 0)

    for i in 0...numOfLinks {
        let link = SKSpriteNode(color: UIColor.black, size: CGSize(width: 20, height: 30))
        link.position = CGPoint(x: anchorSprite.frame.midX, y: anchorSprite.frame.minY - link.frame.height/2)
        link.physicsBody? = SKPhysicsBody(rectangleOf: link.size)
        link.physicsBody?.isDynamic = true
        link.physicsBody?.allowsRotation = true
        link.physicsBody?.affectedByGravity = true
        link.physicsBody?.categoryBitMask = 4
        self.addChild(link)
        var joint = SKPhysicsJointPin()
        links.append(link)
        if i == 0 {
            joint = SKPhysicsJointPin.joint(withBodyA: anchorSprite.physicsBody!, bodyB: link.physicsBody!, anchor: CGPoint(x: anchorSprite.frame.midX, y: anchorSprite.frame.minY))
        } else {
            link.position = CGPoint(x: anchorSprite.frame.midX, y: (links[i-1].frame.minY - links[i-1].frame.height/2) - link.frame.height/2)
            joint = SKPhysicsJointPin.joint(withBodyA: links[i-1].physicsBody!, bodyB: links[i].physicsBody!, anchor: CGPoint(x: links[i-1].frame.minX, y: links[i-1].frame.minY))
        }
        physicsWorld.add(joint)
    }
}

我试图建立一个以编程方式创建一根绳子的功能,到目前为止我可能已经离开了,但是我遇到了问题而且我不明白为什么。

我收到错误"在展开可选&#34时出乎意料地发现nil;

它发生在" Link"当我尝试制作关节时,它的物理体变量。

我不明白为什么,我一直在努力解决这个问题并没有成功。

有人看到代码有什么问题吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您需要移除?的{​​{1}}属性后的physicsBody

旧:

link

新:

link.physicsBody? = SKPhysicsBody(rectangleOf: link.size)