我想在我的应用中检测两个对象之间的联系。我有一个enum
来定义不同的类型:
enum ColliderType: UInt32 {
case Ball = 0b010
case Object = 0b001
case Gap = 0b100
}
我还在SKPhysicsContactDelegate
添加了SKView
:
在didMoveToView
,我有
self.physicsWorld.contactDelegate = self
所以这是我定义的对象
ball = SKSpriteNode(texture: ballTexture)
ball.position = CGPoint(x: CGRectGetMidX(self.frame) - self.frame.width/12, y: self.frame.size.height - (self.frame.size.height - 100))
ball.physicsBody = SKPhysicsBody(circleOfRadius: ballTexture.size().height)
ball.physicsBody!.dynamic = false
ball.physicsBody?.allowsRotation = false
ball.physicsBody!.categoryBitMask = ColliderType.Ball.rawValue
ball.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
ball.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
let boxTexture = SKTexture(imageNamed: "Obstacle.png")
let box1 = SKSpriteNode(texture: boxTexture)
box1.size = CGSizeMake(self.frame.width/4, self.frame.width/8)
box1.runAction(moveAndRemoveBoxes)
box1.physicsBody = SKPhysicsBody(rectangleOfSize: box1.size)
box1.physicsBody!.dynamic = false
box1.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
box1.physicsBody!.contactTestBitMask = ColliderType.Ball.rawValue
box1.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
let gap = SKSpriteNode()
gap.size = box1.size
gap.physicsBody = SKPhysicsBody(rectangleOfSize: box1.size)
gap.physicsBody!.dynamic = false
gap.physicsBody!.categoryBitMask = ColliderType.Gap.rawValue
gap.physicsBody!.contactTestBitMask = ColliderType.Ball.rawValue
gap.physicsBody!.collisionBitMask = ColliderType.Gap.rawValue
在didBeginContact
函数中:
func didBeginContact(contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask == ColliderType.Gap.rawValue || contact.bodyB.categoryBitMask == ColliderType.Gap.rawValue {
print("score")
score++
scoreLabel.text = String(score)
} else {
if gameOver == false {
gameOver = true
self.speed = 0
}
}
}
如果您点击屏幕,球对象会从屏幕的一半跳到另一个屏幕,而名为box1的对象是"掉落"在屏幕的一半和"隐形"检测玩家是否通过而不与盒子发生碰撞的间隙位于屏幕的另一半。所以我想检测球是否碰到了间隙,让球员得分,否则球会与球碰撞
答案 0 :(得分:1)
这是因为你的障碍物contactTestBitMask正在寻找对象,而不是Ball。你想要这个:box1.physicsBody!.contactTestBitMask = ColliderType.Ball.rawValue
鉴于新的变化:
ball.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue | ColliderType.Gap.rawValue
如果您想要联系工作,您需要检查差距值