从两个对象检测SpriteKit上的冲突

时间:2015-08-04 14:42:39

标签: swift sprite-kit collision-detection

当我从我的大炮射击时,我在检测两个物体的碰撞时遇到了一些麻烦。目标是从它射出一颗子弹,并在它与障碍物碰撞时立即移除。似乎游戏中根本没有发生碰撞,因为我无法收到我设置的“碰撞”消息。看看下面的代码:

class GameScene: SKScene, SKPhysicsContactDelegate {


enum BodyType: UInt32 {
    case bullet = 1
    case line = 2
    case breaker = 4
}

我列举了组件,因此我可以在类别Bitmask中设置它们。之后,我在触摸开始时进行了拍摄设置。

 override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    /* Called when a touch begins */

    for touch in (touches as! Set<UITouch>) {

    let bullet = SKSpriteNode(imageNamed: "bullet.png")

    bullet.position = self.shooterTriangle.position

    var actionRotate = SKAction.rotateToAngle(CGFloat(2 * -M_PI), duration: NSTimeInterval(0.1))

    let actionMove = SKAction.moveTo(CGPoint(x: 500, y: size.height * 0.5), duration: NSTimeInterval(0.5))

    let removeBullet = SKAction.removeFromParent()

    bullet.runAction(SKAction.sequence([actionRotate]))

    bullet.runAction(SKAction.sequence([actionMove, removeBullet]))

    addChild(bullet)

        // Bullet Physics Start ****

        bullet.physicsBody? = SKPhysicsBody(circleOfRadius: bullet.size.width/2.0)

        bullet.physicsBody?.dynamic = true
        bullet.physicsBody?.affectedByGravity = false
        bullet.physicsBody?.allowsRotation = false
        bullet.physicsBody?.categoryBitMask = BodyType.bullet.rawValue
        bullet.physicsBody?.contactTestBitMask = BodyType.line.rawValue
        bullet.physicsBody?.collisionBitMask = BodyType.line.rawValue

    }
}

然后我在loadGameComponents函数中添加了我希望子弹与之对齐的行......

func loadGameComponents() {

//Load line....

    let line = SKSpriteNode(imageNamed: "Line_1.png")

    line.position = CGPoint(x: size.width * 0.95, y: size.height * (2.0))

    addChild(line)

    var actualSpeedDuration = 2.2

    let lineActionMove = SKAction.moveTo(CGPoint(x: size.width * 0.95, y: size.height * 0.6), duration: NSTimeInterval(actualSpeedDuration))

    line.runAction(SKAction.sequence([lineActionMove]))

    // Line Physics starts! *****

    line.physicsBody? = SKPhysicsBody(rectangleOfSize: CGSize(width: line.size.width, height: line.size.height))

    line.physicsBody?.dynamic = false
    line.physicsBody?.affectedByGravity = false
    line.physicsBody?.allowsRotation = false
    line.physicsBody?.categoryBitMask = BodyType.line.rawValue
    line.physicsBody?.contactTestBitMask = BodyType.bullet.rawValue
    line.physicsBody?.collisionBitMask = 0

最后,我在didLoad函数中定义了contactDelegate = self并包含了didBeginContact方法

func didBeginContact(contact: SKPhysicsContact) {
    println("Contact!!!")
}

我根本没有收到消息,但我不确定出了什么问题!

感谢您的耐心等待! :)

1 个答案:

答案 0 :(得分:2)

看起来主要问题是我在声明精灵的物理主体时曾经放置了可选指示符(?)。应该按照这条线进行修正......

line.physicsBody? = SKPhysicsBody(rectangleOfSize: CGSize(width: line.size.width, height: line.size.height))

bullet.physicsBody? = SKPhysicsBody(circleOfRadius: bullet.size.width/2.0)

删除它们解决了我的问题:)

我还在myMoveToView方法中包含view.showPhysics = true,因此很容易看到精灵之间的界限。