首页 > 解决方案 > 如何检查一个节点是否靠近另一个节点?

问题描述

一段时间以来,我一直试图在一个节点靠近另一个节点时调用一个函数。为此,我首先处理了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
    } 
}

我将非常感谢任何答案。

标签: swiftsprite-kit

解决方案


推荐阅读