首页 > 解决方案 > 没有调用 didBegin

问题描述

我的目标是输出“命中”,但不改变cardand的位置anotherCard。他们应该互相接触,但不能移动。但是没有调用 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

解决方案


要在 2 个节点接触时收到通知,但不让它们移动,那么您需要在节点之间打开接触检测(这样做didBegin被称为)但关闭碰撞检测(因为是碰撞导致节点在他们接触)。

这是通过正确设置collisionBitMaskand来完成的contactTestBitMask

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

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

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

操作位掩码以关闭和打开单独的碰撞和接触。 https://stackoverflow.com/a/46495864/1430420

编辑:

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

尝试将其定义更改为:

结构 physicBodyCharacters {

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

推荐阅读