ios - SKSpriteNode 子类 : method to remove all joints

标签 ios swift sprite-kit skphysicsbody skphysicsjoint

我创建了一个 SKSpriteNode 的子类。我将该类的实例与 SKPhysicsJointLimit 类型的关节连接在一起。我在 GameScene 的 didEndContact(contact: SKPhysicsContact) 中执行此操作:

var joint = SKPhysicsJointLimit.jointWithBodyA(contact.bodyA, bodyB: contact.bodyB, anchorA: pos1!, anchorB: pos2!)
self.physicsWorld.addJoint(joint)

目前效果很好。 然后我到了要从关节释放节点的地步。 According to the SKPhysicsBody docs there is a property called "joints" which is an array holding SKPhysicsJoint objects.我认为这正是我所需要的,但我无法遍历实例的关节并将它们从物理世界中移除。为了完成这项工作,我向我的自定义 SKSpriteNode 子类添加了一个方法。

func freeJoints(world: SKPhysicsWorld){
        if let joints = self.physicsBody?.joints {
            for joint in joints{
                println("found a joint: \(joint)")
                // example print:
                //found a joint: <PKPhysicsJointRope: 0x7fbe39e95c50>
                world.removeJoint(joint as SKPhysicsJoint)
            }
        }
    }

调用方法在 println() 语句后失败并显示消息“Swift dynamic cast failed”。我非常感谢您对如何使用 SKPhysicsBody 的共同属性(property)提出意见。更具体地说:如何使用(转换?)数组中的项目以便能够将它们从场景的 SKPhysicsWorld 中移除。

最佳答案

我花了更多时间对此进行调查。这是我想出的:

我决定向我的 SKSpriteNode 子类添加一个属性并自己管理关节

    var joints: [SKPhysicsJointLimit]
override init(){
    ...
    self.joints = []
    ...
}

每次我向场景的 SKPHysicsWorld 添加一个关节时,我也会将它添加到 SKNNode 本身的关节数组中。在我想将 SKPHysicsBody 的关节数组迭代失败(参见问题)时,我想将其转换为 SKPhysicsJoint,在迭代 SKPhysicsJointLimit 项目数组时,从物理世界中删除项目按预期工作:

func freeJoints(world: SKPhysicsWorld){
        for item in self.joints{
            println("removing item from physics world \(item)")
            world.removeJoint(item)
        }
        self.joints.removeAll(keepCapacity: false)
    }
}

这似乎不是完成这项工作的最优雅的方式,因为已经有一个框架管理的数组 promise 做同样的事情。但我无法使用它,但目前可以使用。

关于ios - SKSpriteNode 子类 : method to remove all joints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27649362/

相关文章:

arrays - 替换 2 个数组的元素?

xcode - 如何检测 spritekit 中的触摸?

ios - 使用 SpriteKit 定位 Sprite 的最佳实践

ios - 在 CABasicAnimation 中使用 #keyPath 时,类型 'CGPoint' 没有成员 'x'

ios - Facebook 在 iOS 上不显示 map

ios - SpriteKit 中自定义绘图的替代方案有哪些?

swift - 使用Sprite Kit中TileMap的物体位置

ios - 使用 swift 4.2 动画 UIView

ios - Apple 新的 Kids Section 家长控制问题

ios - 即使登录错误也能登录