我正在製作一個遊戲,我需要我的spriteNodes發生碰撞。我跟着一個教程,但它只是不適合我。didBeginContact不叫
當我運行我的遊戲和兩個對象發生碰撞時,輸出監視器中沒有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()
}
通常不調用函數的問題是因爲未設置.delegate屬性。 – JMFR 2014-10-30 13:51:35
是你需要設置場景作爲物理世界代表 – LearnCocos2D 2014-10-30 14:47:36
你的意思是這樣的:class GameScene:SKScene,SKPhysicsContactDelegate { – Murturn 2014-10-30 14:52:00