didBegin没有被调用

时间:2018-12-02 12:31:26

标签: swift sprite-kit

我的目标是输出“命中” ,但不更改cardanotherCard的位置。他们应该彼此碰触,但不能移动。但是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
    } 
}

对于每个答案我都很感谢。

1 个答案:

答案 0 :(得分:1)

要在2个节点接触时得到通知,但又不让它们移动,则需要在节点之间打开接触检测功能(执行didBegin),但要关闭碰撞检测功能(因为导致节点在触摸时移动的碰撞。

这是通过正确设置collisionBitMaskcontactTestBitMask来完成的。

您尚未发布足够的代码供我们检查,但您可能需要阅读以下有关其他类似问题的答案:

有关碰撞和接触的分步指南: https://stackoverflow.com/a/51041474/1430420

以及碰撞和接触的指南测试位掩码: https://stackoverflow.com/a/40596890/1430420

操纵位掩码以打开和关闭各个碰撞和接触。 https://stackoverflow.com/a/46495864/1430420

编辑:

我认为您的类别定义是错误的-它们应该是二进制位掩码,但您已将它们定义为小数。

尝试将其定义更改为:

struct physicBodyCharacters {

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