我有3个精灵可以相互碰撞并设置contactTestBitMask
和categoryBitMask
。
我有两个精灵使用didBeginContact
方法来查看它们是否已经碰撞并且工作正常,但现在我不知道如何设置它来检查多个对象的联系人并运行不同的功能,具体取决于哪两个身体碰撞。
我的PhysicsCategory
:
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
}
didBeginContact
中的GameScene
方法:
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联系,在这种情况下,我没有写一个函数来做什么,但是稍后,我会为这种情况调用一个不同的函数。我还添加了一些额外的精灵,所以如果有人能解释如何为代码写好并且不会导致任何错误,我将不胜感激。
答案 0 :(得分:2)
您可以检查鸟是否与书桌联系
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
}
Bird与starSpecial联系
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
}
请注意:变量应以小写字母开头。
为了保持代码清晰,我建议为每个节点创建类文件。
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")
}
}
然后像这样添加
var monster = Monster.init(world)
world.addChild(monster)