【问题标题】:error when 2 nodes collide2个节点碰撞时出错
【发布时间】:2015-01-18 22:15:36
【问题描述】:

当 2 个节点发生碰撞时,我不断收到错误消息,这是我用于碰撞检测的代码:

func didBeginContact(contact: SKPhysicsContact!) {

    var firstBody:SKPhysicsBody
    var secondBody:SKPhysicsBody

    if(contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask){
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }else{
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }


        if((firstBody.categoryBitMask & coin2Category) != 0 && (secondBody.categoryBitMask & playerCategory) != 0){
            var bodyAAC = contact.bodyA.node as SKSpriteNode //error pointing at this line: fatal error: unexpectedly found nil while unwrapping an optional value
            if CGRectIntersectsRect(kikker.frame, bodyAAC.frame) {
                coinslos = coinslos + 10
                coinlabel.text = "\(coinslos)"
                bodyAAC.removeFromParent()
                coinSound()
            }
        }
}

我做错了什么?

【问题讨论】:

  • 可能contact.bodyA.node 不是SKSpriteNode。您正在检查碰撞的物体类型是什么?

标签: swift sprite-kit collision-detection skphysicsbody


【解决方案1】:

首先要避免崩溃

这个:

        var bodyAAC = contact.bodyA.node as SKSpriteNode
        if CGRectIntersectsRect(kikker.frame, bodyAAC.frame) {
            coinslos = coinslos + 10
            coinlabel.text = "\(coinslos)"
            bodyAAC.removeFromParent()
            coinSound()
        }

应该改成这样:

        if let bodyAAC = contact.bodyA.node as? SKSpriteNode {
            if CGRectIntersectsRect(kikker.frame, bodyAAC.frame) {
                 coinslos = coinslos + 10
                 coinlabel.text = "\(coinslos)"
                 bodyAAC.removeFromParent()
                 coinSound()
            }
        }

在尝试使用它们之前,您需要检查选项。

但是 rakeshbs 是正确的。无论发生哪种碰撞,bodyA.node 都不是 SKSpriteNode。我不知道您的代码的细节,但您没有使用或访问任何 SKSpriteNode 特定的属性/方法。

你可以尝试改变:

            if let bodyAAC = contact.bodyA.node as? SKSpriteNode {

收件人:

            if let bodyAAC = contact.bodyA.node {

如果这仍然不起作用,那么它看起来根本不像 bodyA 附加到任何节点。

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2015-01-21
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2022-10-04
    相关资源
    最近更新 更多