我为每个我想要彼此交互的不同对象创建了一个struct PhysicsCatagory
struct PhysicsCatagory {
static let Blade : UInt32 = 1
static let Laser : UInt32 = 2
}
在我的GameScene上面
class GameScene: SKScene, SKPhysicsContactDelegate {
我在didMoveToView方法中使用physicsBody初始化了一个SKSpriteNode刀片
override func didMoveToView(view: SKView) {
physicsWorld.contactDelegate = self
Blade.position = CGPointMake(self.size.width / 2, (self.size.height / 14))
Blade.anchorPoint = CGPointMake(0.5, -0.13)
Blade.physicsBody = SKPhysicsBody(rectangleOfSize: Blade.size)
Blade.physicsBody?.categoryBitMask = PhysicsCatagory.Blade
Blade.physicsBody?.contactTestBitMask = PhysicsCatagory.Laser
Blade.physicsBody?.dynamic = false
self.addChild(Blade)
}
与方法shootLaser
中的SKSpriteNode激光及其物理实体一样func shootLaser(){
var Laser = SKSpriteNode(imageNamed: "Laser.png")
Laser.position = Enemy.position
Laser.zPosition = -5
Laser.physicsBody = SKPhysicsBody(rectangleOfSize: Laser.size)
Laser.physicsBody?.categoryBitMask = PhysicsCatagory.Laser
Laser.physicsBody?.contactTestBitMask = PhysicsCatagory.Blade
Laser.physicsBody?.dynamic = false
let action = SKAction.moveBy(laserVector, duration: 0.7)
let actionDone = SKAction.removeFromParent()
Laser.runAction(SKAction.sequence([action,actionDone]))
self.addChild(Laser)
}
但是当它们在模拟中发生碰撞时,不会调用didBeginContact方法并且不打印“Hello”
func didBeginContact(contact: SKPhysicsContact) {
NSLog("Hello")
}
为什么在碰撞时不会调用didBeginContact方法?提前致谢(:
答案 0 :(得分:3)
Sprite Kit不会检查非动态物理实体之间的接触,因为它们不会移动。如果您不希望精灵因重力而从屏幕上掉下来,请将物理主体的affectedByGravity
属性设置为false
并设置dynamic = true
。