3个节点之间的联系

时间:2015-07-13 04:12:19

标签: ios arrays swift sprite-kit nsarray

我正在尝试检测3个节点之间是否存在联系。我的检查过程如下:

  1. 使用didBeginContact获取刚刚联系的两个节点名称。
  2. 有一个数组,用于存储彼此接触的所有节点名称。检查firstBody.namesecondBody.name是否已在数组中
  3. 如果是,请删除firstBodysecondBody以及节点与其父节点联系的节点。
  4. 我的代码如下:

    class GameScene: SKScene, SKPhysicsContactDelegate {
    var arrayOfContacts: [AnyObject] = []
    
    func didBeginContact(contact: SKPhysicsContact) {
            let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
            contact.bodyA.node?.physicsBody?.allowsRotation = true
            contact.bodyB.node?.physicsBody?.allowsRotation = true
    
        switch(contactMask) {
        //at this point I am only looking to detect contact between 3 squares, hence the switch statement
    
        case CollisionCategoryBitmask.square | CollisionCategoryBitmask.square:
    
            var firstBody: SKNode!
            var secondBody: SKNode!
    
            if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
                firstBody = contact.bodyA.node
                secondBody = contact.bodyB.node
            }
            else {
                firstBody = contact.bodyB.node
                secondBody = contact.bodyA.node
            }
    
            var individualContact: [Int] = []
            individualContact.append(firstBody.name!.toInt()!)
            individualContact.append(secondBody.name!.toInt()!)
    
            for subArray in arrayOfContacts {
                for name in subArray as! NSArray {
                    if name as? Int == firstBody.name?.toInt() || name as? Int == secondBody.name?.toInt() {
                        println("this is connected to some others")
                        //this is where i would put in code to remove firstBody, secondBody and the other node from their parent
    
                    }
                    else {
                        println("not an already known contact, adding it to arrayOfContacts")
                        //this is where I would append individualContact to arrayOfContacts
                    }
                }
            }
            default: break
        }}}
    

    每次有新联系人时,我首先检查其中一个联系人是否在arrayOfContacts中。如果是,我将把它们从父母那里删除,如果我不将它们添加到联系人数组中。

    我试图给出尽可能好的代码印象。虽然我没有包含它,但我也有func didEndContact检查两个已分离的节点是否在arrayOfContacts中。如果是这样,它们将从阵列中删除。

0 个答案:

没有答案