未制作接触和碰撞位掩码

时间:2017-09-20 16:12:49

标签: ios swift swift3 collision-detection collision

我一直试图在他们联系的模拟器中的两个节点之间建立联系但是没有接触检测。我尝试了很多方法,但都没有。这是代码

var location = CGPoint( x :0 ,y : 0)
class GameScene: SKScene , SKPhysicsContactDelegate {

      override func didMove(to view: SKView) {
        self.physicsWorld.gravity = CGVector.init(dx: 0.0, dy: 0.0)
        addcircle ()
        addobst () 
        physicsWorld.contactDelegate = self
    }

    func addcircle () {
        let circle = SKShapeNode(circleOfRadius: 100)

        circle.fillColor = UIColor.red
        circle.name = " CIRCLE "

        circle.physicsBody?.isDynamic = true
        circle.physicsBody?.categoryBitMask = contactcategory.circle.rawValue
        circle.physicsBody?.collisionBitMask = contactcategory.obstacle.rawValue
       circle.physicsBody?.contactTestBitMask = contactcategory.obstacle.rawValue

        circle.position = location
        circle.physicsBody = SKPhysicsBody.init(circleOfRadius: 100)

        addChild(circle)
    }

    func addobst () {
        let A = Double(arc4random_uniform(70))

        let obstacle = SKSpriteNode(color: UIColor.white, size : CGSize(width: A, height : A))

        obstacle.name = "OBSTACLE"
        obstacle.physicsBody?.isDynamic = true
        obstacle.physicsBody?.categoryBitMask = contactcategory.obstacle.rawValue
        obstacle.physicsBody?.collisionBitMask = contactcategory.circle.rawValue
        obstacle.physicsBody?.contactTestBitMask = contactcategory.circle.rawValue

        let randomx = Double(arc4random_uniform(UInt32(self.size.width)))
        if randomx >= Double((self.size.width)/2) {
            obstacle.position = CGPoint( x : randomx - A ,y : Double(self.size.height) + A)
        } else if randomx <= Double((self.size.width)/2) {
            obstacle.position = CGPoint( x : randomx + A ,y : Double(self.size.height) + A)
        }
        obstacle.physicsBody = SKPhysicsBody.init(rectangleOf: obstacle.size)

        var actionArray = [SKAction]()
        actionArray.append(SKAction.move(to: CGPoint( x : obstacle.position.x ,y : -obstacle.size.height ), duration:3 ))
        actionArray.append(SKAction.removeFromParent())
        obstacle.run(SKAction.sequence(actionArray))
        addChild(obstacle)

    func didBegin(_ contact: SKPhysicsContact) {

        let contactmask = contact.bodyA.categoryBitMask
        let contactmask1 = contact.bodyB.categoryBitMask

        if ((contactmask == contactcategory.obstacle.rawValue) && ( contactmask1 == contactcategory.circle.rawValue )) {
            print("contact made")
        } else if ((contactmask == contactcategory.circle.rawValue) && ( contactmask1 == contactcategory.obstacle.rawValue )) {
            print("contact made")
        }
    }
}

0 个答案:

没有答案