Swift/SpriteKit - 碰撞和物体

Swift/SpriteKit - Collisions and Objects

我有一个class叫做Item,里面有一个叫做itemNode的实例变量,它的类型是SKSpriteNode。在我的 GameScene class 中,当我创建 Item 的实例时,我创建了一个提供给 Item 的 itemNode 的物理体。在我的碰撞检测系统中,当我的角色的物理体与 itemNode 的物理体发生碰撞时,我想在节点的物理体刚刚发生碰撞的 Item 对象上执行一个函数。但是,碰撞系统只returns到物理体。如何访问仅给出节点物理体的 Item 对象?

SKPhyicsBody class 有一个 node property 指向它所附加的 SKNode 实例。

您的碰撞检测代码可能如下所示:

func didBeginContact(contact: SKPhysicsContact) {

    var item: SKSpriteNode
    var character: SKSpriteNode

    //Change this on the basis of the order of your categoryBitMask values
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
    {
        item = contact.bodyA.node as SKSpriteNode
        character = contact.bodyB.node as SKSpriteNode
    }
    else
    {
        item = contact.bodyB.node as SKSpriteNode
        character = contact.bodyA.node as SKSpriteNode
    }

    //Perform necessary operations on item and character
}

编辑: 为了访问声明节点的 Item 实例,您必须在指向 Item 实例的节点中存储一个变量。为此,您可以子 class SKSpriteNode 并包含一个 属性,或者使用 userData 属性 的 SKNode

子classing:

//New Class
class ItemNode: SKSpriteNode {

    static var itemInstance
}

//In the Item class declare the itemNode using this class
let itemNode = ItemNode()
itemNode.itemInstance = self

用户数据属性:

item.userData = NSMutableDictionary(object: self, forKey: "ItemInstance"))