如何检查一个节点是否靠近另一个节点?

时间:2018-12-16 15:15:15

标签: swift sprite-kit

一段时间以来,当一个节点靠近另一个节点时,我一直试图调用一个函数。为此,我首先处理了SKPhysicBody,但是由于从未调用过didBegin()函数,因此我想问问是否有人有其他想法,如何轻松地检查一个节点是否靠近另一个节点。

结构:

struct physicBodyCharacters {

    static let cardNumber = 00000001 //1
    static let anotherCardNumber = 00000010 //2
    static let nobodyNumber = 00000100 //4
}

在viewDidLoad()中:

gameScene2.physicsWorld.gravity = CGVector(dx: 0, dy: -9.81)
    gameScene2.physicsWorld.contactDelegate = self

第一个节点:

card = SKSpriteNode(texture: cardTexture)
    card.position = CGPoint(x: gameScene2.size.width / 2 + 150, y: 95)
    card.zPosition = 3
    card.setScale(1)
    card.physicsBody = SKPhysicsBody(texture: cardTexture, size: card.size)
    card.physicsBody?.affectedByGravity = false
    card.physicsBody?.categoryBitMask = UInt32(physicBodyCharacters.cardNumber)
    card.physicsBody?.collisionBitMask = UInt32(physicBodyCharacters.nobodyNumber)
    card.physicsBody?.contactTestBitMask = UInt32(physicBodyCharacters.anotherCardNumber)

第二个节点:

anotherCard = SKSpriteNode(texture: anotherCardTexture)
    anotherCard.position = CGPoint(x: 31 , y: 532)
    anotherCard.zPosition = 2
    anotherCard.setScale(1)
    anotherCard.physicsBody = SKPhysicsBody(texture: anotherCardTexture, size: battlefieldCard0.size)
    anotherCard.physicsBody?.affectedByGravity = false
    anotherCard.physicsBody?.categoryBitMask = UInt32(physicBodyCharacters.anotherCardNumber)
    anotherCard.physicsBody?.collisionBitMask = UInt32(physicBodyCharacters.nobodyNumber)
    anotherCard.physicsBody?.contactTestBitMask = UInt32(physicBodyCharacters.cardNumber)

didBegin()函数:

func didBegin(_ contact: SKPhysicsContact) {
    print("contact")
    let contanctMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch contanctMask
    {
    case UInt32(physicBodyCharacters.cardNumber) | UInt32(physicBodyCharacters.anotherCardNumber):
        print("hit")
    default:
        break
    } 
}

我将非常感谢您提供任何答案。

0 个答案:

没有答案