The proper way of using didBeginContact in SpriteKit games - Swift
我有 3 个sprite,它们可以相互碰撞并设置了
我有两个使用
我的
1 2 3 4 5 6 7 8 9 | struct PhysicsCategory { static let None: UInt32 = 0 static let All: UInt32 = UInt32.max static let Bird: UInt32 = 0b1 static let Cloud: UInt32 = 0b10 static let Desk: UInt32 = 0b100 static let Star: UInt32 = 0b101 static let StarSpecial: UInt32 = 0b110 } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | func didBeginContact(contact: SKPhysicsContact) { var BirdBody: SKPhysicsBody? var DeskBody: SKPhysicsBody? var SpecialStarBody: SKPhysicsBody? //var SpecialStarBody: SKPhysicsBody if contact.bodyA.categoryBitMask == PhysicsCategory.Bird { BirdBody = contact.bodyA DeskBody = contact.bodyB } else if contact.bodyA.categoryBitMask == PhysicsCategory.Desk { BirdBody = contact.bodyB DeskBody = contact.bodyA } else if contact.bodyA.categoryBitMask == PhysicsCategory.StarSpecial { SpecialStarBody = contact.bodyA } if (DeskBody != nil) { birdSprite.BirdDidCollideWithDesk(BirdBody?.node as! Bird, desk: DeskBody?.node as! Desk, scoreClass: scoreClass, scoreLabel: scoreLabel) } } |
我要做的是检查鸟是否与桌子接触,在这种情况下,它应该运行鸟和桌子的功能,否则我想查看鸟是否接触到 SpecialStar,我还没有写一个函数来说明在这种情况下要做什么,但是稍后我会为这种情况调用一个不同的函数。我还添加了一些额外的sprite,所以如果有人能解释如何做到这一点以使代码写得很好并且不会导致任何错误,我将不胜感激。
您可以检查鸟是否与桌子接触
1 2 3 4 5 6 | if ((contact.bodyA.categoryBitMask == PhysicsCategory.Bird && contact.bodyB.categoryBitMask == PhysicsCategory.Desk) || (contact.bodyA.categoryBitMask == PhysicsCategory.Desk && contact.bodyB.categoryBitMask == PhysicsCategory.Bird)) { print("Bird, desk") // Handle contact bird with desk } |
鸟接触starSpecial
1 2 3 4 5 6 | if ((contact.bodyA.categoryBitMask == PhysicsCategory.Bird && contact.bodyB.categoryBitMask == PhysicsCategory.StarSpecial) || (contact.bodyA.categoryBitMask == PhysicsCategory.Desk && contact.bodyB.categoryBitMask == PhysicsCategory.StarSpecial)) { print("Bird, StarSpecial") // Handle contact bird with StarSpecial } |
Just a note: Variables should start with a lowercase letter.
为了保持代码清晰,我建议为每个节点创建类文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import Foundation import SpriteKit class Monster: SKSpriteNode { init(world: SKNode) { super.init(texture: SKTexture(imageNamed:"MonsterImageName"), color: UIColor.clearColor(), size: CGSizeMake(world.frame.size.width / 18, world.frame.size.width / 36)) position = CGPointMake(world.frame.size.width / 2, world.frame.size.height / 2) zPosition = 100 // etc } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } |
然后像这样添加它
1 2 | var monster = Monster.init(world) world.addChild(monster) |