【问题标题】:Confusing issue adding and removing SKPhysicsJointPin upon touch触摸时添加和删除 SKPhysicsJointPin 的令人困惑的问题
【发布时间】:2016-07-06 03:53:33
【问题描述】:

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

    }
}

【问题讨论】:

  • 可以用if let joint = head.physicsBody?.joints.first { self.physicsWorld.removeJoint(joint) }删除touchesBegan中的关节

标签: ios xcode swift sprite-kit skphysicsjoint


【解决方案1】:

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

    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)
         }
    }

【讨论】:

  • 我昨天找到了解决方案,实际上它与这个答案非常相似,感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多