SKPhysicsContact未检测到categoryBitMask碰撞

时间:2017-12-22 19:23:17

标签: swift sprite-kit skphysicscontact

所以我的“Floor.swift”课程下面基本上是一堆墙。我有来自屏幕顶部的对象,一旦Floor和SKSpriteNodes发生碰撞,我希望删除SKSpriteNode。以下是我的楼层课程。

import Foundation
import SpriteKit

    class Floor: SKNode {
        override init() {
            super.init()

            let leftWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 5, height: 50))
            leftWall.position = CGPoint(x: 0, y: 50)
            leftWall.physicsBody = SKPhysicsBody(rectangleOf: leftWall.size)
            leftWall.physicsBody!.isDynamic = false
            self.addChild(leftWall)

            let rightWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 5, height: 50))
            rightWall.position = CGPoint(x: 375, y: 50)
            rightWall.physicsBody = SKPhysicsBody(rectangleOf: rightWall.size)
            rightWall.physicsBody!.isDynamic = false
            self.addChild(rightWall)

            let bottomWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 500, height: 10))
            bottomWall.position = CGPoint(x: 150, y: -5)
            bottomWall.physicsBody = SKPhysicsBody(rectangleOf: bottomWall.size)
            bottomWall.physicsBody!.isDynamic = false
            self.addChild(bottomWall)

            // Set the bit mask properties
            self.physicsBody?.categoryBitMask = floorCategory
            self.physicsBody?.contactTestBitMask = objectCategory | pointCategory | lifeCategory
            self.physicsBody?.collisionBitMask = dodgeCategory
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemted")
        }
    } 

然后在“func didBegin(_ contact: SKPhysicsContact)”下的我的GameScene课程中,我写道:

 if (contact.bodyA.categoryBitMask == floorCategory) && (contact.bodyB.contactTestBitMask == objectCategory | pointCategory | lifeCategory) {
              contact.bodyB.node!.removeFromParent()
              print("COLLISION")
}

但由于某种原因,我没有得到任何检测。我在我的objectCategory,pointCategory,lifeCategory的每个类上使我的“Floor”类成为“contactTestBitMask”。我究竟做错了什么!?检测到我的其他碰撞,但没有检测到。

1 个答案:

答案 0 :(得分:3)

您的leftWallrightWallbottomWall具有默认的contactTestcollision位掩码,因此会与所有内容发生冲突并生成无任何联系人。除非他们都将isDynamic属性设置为false,否则他们无法与任何内容发生冲突或联系(尽管其他内容可能会发生碰撞并与其联系,如果其他内容已设置为isDynamic true)。

但这可能是你想要的(地板和墙壁通常不是动态的)。我怀疑真正的问题是Floor类的对象没有物理体,除非你在其他地方初始化它。你有以下几行:

self.physicsBody?.categoryBitMask = ... self.physicsBody?.contactTestBitMask = ... self.physicsBody?.collisionBitMask = ...

但您实际上并未创建self.physicsBody。你的代码会崩溃,除非你使用了可选的链接(self,phyicsBody?),因此Swift进入'?'并说“哦 - 它是可选的,不存在。我会在这里停下来“

至少,尝试使用3个墙体对象的物理体为Floor对象创建物理体:

Self.physicsBody = SKPhysicsBody(Bodies: [leftWall.physicsBody, rightWall.PhysicsBoidy, bottomWall.physicsBody])

(SKPhysicsBody有一个初始化器,它需要一组物理体来创建一个新的物理体)。