didBeginContact未调用

Mur*_*urn 2 collision sprite-kit swift

我正在制作一个我需要我的spriteNodes碰撞的游戏.我按照教程,但它不适合我.

当我运行我的游戏并且两个对象发生碰撞时,输出监视器中没有println("beginContact"),因此不会调用didBeginContact函数.

override init(size:CGSize) {
    super.init(size: size)
    player.planeSprite = SKSpriteNode(imageNamed: "plane5")

    player.planeSprite.physicsBody? = SKPhysicsBody(rectangleOfSize: player.planeSprite.size)
    player.planeSprite.physicsBody?.dynamic = true;
    player.planeSprite.physicsBody?.categoryBitMask = playerCategory;
    player.planeSprite.physicsBody?.contactTestBitMask = noteCategory;
    player.planeSprite.physicsBody?.collisionBitMask = 0;
    player.planeSprite.physicsBody?.usesPreciseCollisionDetection = true;

    player.planeSprite.position = CGPointMake(player.legalPositions[1], player.planeSprite.size.height/2)

    self.addChild(player.planeSprite)
}

func addNote() {
    var note:SKSpriteNode = SKSpriteNode(imageNamed: "note")
    note.physicsBody? = SKPhysicsBody(rectangleOfSize: note.size)
    note.physicsBody?.dynamic = true
    note.physicsBody?.categoryBitMask = noteCategory
    note.physicsBody?.contactTestBitMask = playerCategory
    note.physicsBody?.collisionBitMask = 0

    let minX = note.size.width/2
    let maxX = self.frame.size.width - note.size.width/2
    let rangeX = maxX - minX
    let position = Int(arc4random_uniform(3))

    note.position = CGPointMake(player.legalPositions[position], self.frame.size.height + note.size.height)

    self.addChild(note)
}

func didBeginContact(contact: SKPhysicsContact!) {
    println("beginContact")

    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 & noteCategory) != 0 && (secondBody.categoryBitMask & playerCategory) != 0 ) {
        println("if statement")
        playerDidCollideWithNote(firstBody.node as SKSpriteNode, note: secondBody.node as SKSpriteNode)
    }
}

func playerDidCollideWithNote(plane:SKSpriteNode, note:SKSpriteNode) {
    println("hit")
    note.removeFromParent()
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*ing 12

做了好几次这个错误.

首先需要从SKPhysicsContactDelegate继承:

class GameScene: SKScene, SKPhysicsContactDelegate { ... }
Run Code Online (Sandbox Code Playgroud)

然后在您的didMoveToView方法中添加:

override func didMoveToView(view: SKView) {
    self.physicsWorld.contactDelegate = self
}
Run Code Online (Sandbox Code Playgroud)

将GameScene实例设置为physicsWorld的contactDelegate.


小智 11

如果您使用Xcode8.0 Swift3.0,则无法使用
func didBeginContact(contact: SKPhysicsContact!) {}

所以你应该使用它. func didBegin(_ contact: SKPhysicsContact) {}