检测碰撞SpriteKit Swift

时间:2016-01-20 15:22:39

标签: xcode swift sprite-kit collision-detection

碰撞检测不会在didBeginContact函数中调用NSLog。物理学工作得很好......有人能告诉我我做错了什么吗?我尝试的一切都给了我同样的结果。

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

let category0: UInt32 = 0x1 << 0
let category1: UInt32 = 0x1 << 1
let category2: UInt32 = 0x1 << 2
let category3: UInt32 = 0x1 << 4
let position1:CGFloat = 100

override func didMoveToView(view: SKView) {

    self.physicsBody = SKPhysicsBody (edgeLoopFromRect:self.frame)
    self.physicsWorld.gravity = CGVectorMake(0, -9)
    physicsWorld.contactDelegate = self

    let ground = SKSpriteNode(color: UIColor .redColor(), size: CGSizeMake(self.size.width, self.size.height/16))
    ground.position = CGPointMake(self.size.width/2, self.size.height - self.size.height + ground.size.height)
    ground.zPosition = position1
    self.addChild(ground)
    ground.physicsBody = SKPhysicsBody(rectangleOfSize: ground.size)
    ground.physicsBody?.categoryBitMask = category2
    ground.physicsBody?.contactTestBitMask = category1
    ground.physicsBody?.collisionBitMask = category1
    ground.physicsBody?.dynamic = false
    ground.physicsBody?.affectedByGravity = false
    ground.name = "Ground"

    let launchingPad = SKSpriteNode(color: UIColor .redColor(), size: CGSizeMake(self.size.width/6, self.size.height/16))
    launchingPad.position = CGPointMake(self.size.width - launchingPad.size.width/2 - 5, self.size.height - self.size.height + launchingPad.size.height * 4)
    launchingPad.zPosition = position1
    self.addChild(launchingPad)
    launchingPad.physicsBody = SKPhysicsBody(rectangleOfSize: launchingPad.size)
    launchingPad.physicsBody?.categoryBitMask = category1
    launchingPad.physicsBody?.contactTestBitMask = category2
    launchingPad.physicsBody?.collisionBitMask = category2
    launchingPad.physicsBody?.dynamic = true
    launchingPad.physicsBody?.affectedByGravity = true
    launchingPad.name = "LaunchingPad"

    func didBeginContact(contact: SKPhysicsContact) { 

        let firstBody = contact.bodyA.node as! SKSpriteNode

        let secondBody = contact.bodyB.node as! SKSpriteNode

        if ((firstBody.name == "LaunchingPad") && (secondBody.name == "Ground")){

NSLog("Contact")

}}}}

1 个答案:

答案 0 :(得分:2)

根据KnightOfDragon评论回答我自己的问题。这是工作方法。

func didBeginContact(contact: SKPhysicsContact) {

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 == category1) && (secondBody.categoryBitMask == category2)){
    NSLog("contact")
}
}