混淆问题在触摸时添加和删除SKPhysicsJointPin

时间:2016-07-06 03:53:33

标签: ios xcode swift sprite-kit skphysicsjoint

我在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)

    }
}

1 个答案:

答案 0 :(得分: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)
         }
    }