2

我在 touchesBegan 函数中添加和删除我的 SKPhysicsJointPin 时遇到问题。问题是我的关节是在 didMoveToView 函数中声明的,因为它需要根据其中存在的表达式进行定位。

既然如此,我就不能在 touchesBegan 函数中引用 SKPhysicsJoint ,这对于我试图用我的项目做的事情是必要的。有什么解决方案或建议吗?

代码:

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    var head = SKSpriteNode(imageNamed: "crown.png")
    var headTexture = SKTexture(imageNamed: "crown.png")

    var neck = SKSpriteNode(imageNamed: "throat.png")
    var neckTexture = SKTexture(imageNamed: "throat.png")

    override func didMoveToView(view: SKView) {

        head.position.x = torso.position.x - 1
        head.position.y = torso.position.y + 77
        head.physicsBody = SKPhysicsBody(texture: headTexture, size: head.size)
        head.physicsBody!.categoryBitMask = ColliderType.part.rawValue
        head.physicsBody!.contactTestBitMask = ColliderType.part.rawValue
        head.physicsBody!.collisionBitMask = ColliderType.part.rawValue
        self.addChild(head)

        neck.position.x = torso.position.x
        neck.position.y = torso.position.y + 44
        neck.physicsBody = SKPhysicsBody(texture: neckTexture, size: neck.size)
        neck.physicsBody!.categoryBitMask = ColliderType.mjoint.rawValue
        neck.physicsBody!.contactTestBitMask = ColliderType.mjoint.rawValue
        neck.physicsBody!.collisionBitMask = ColliderType.mjoint.rawValue
        self.addChild(neck)

        let headToNeck = SKPhysicsJointPin.jointWithBodyA(head.physicsBody!, bodyB:neck.physicsBody!, anchor:CGPointMake(head.position.x, head.position.y - 20.8))
        headToNeck.shouldEnableLimits = true
        self.physicsWorld.addJoint(headToNeck)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        self.physicsWorld.removeJoint(headToNeck)

    }
}
4

1 回答 1

0

尝试像这样创建一个类变量:

    class GameScene: SKScene, SKPhysicsContactDelegate {   

        var headToNeck: SKPhysicsJoint!
        //other variables

        override func didMoveToView(view: SKView) {
            //other code
            self.headToNeck = SKPhysicsJointPin.jointWithBodyA(head.physicsBody!, bodyB:neck.physicsBody!, anchor:CGPointMake(head.position.x, head.position.y - 20.8))
            self.headToNeck.shouldEnableLimits = true
            self.physicsWorld.addJoint(self.headToNeck)
        }

         override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            self.physicsWorld.removeJoint(self.headToNeck)
         }
    }
于 2016-07-07T12:34:32.597 回答