使用 Swift 在 Sprite Kit 中进行碰撞检测

Collision Detection In Sprite Kit using Swift

下面的代码来自我目前正在做的一个项目,这几天我一直在努力自学Swift语言和Sprite Kit,这是我第一次尝试游戏,它是一个 Flappy Bird 类型的游戏。今天我在尝试编写碰撞检测代码时遇到了一个问题。当小鸟接触其中一根管道时,游戏应该暂停。但是,当我运行代码并且小鸟接触到管道时,什么也没有发生,小鸟只是从管道上弹开。我已经阅读了很多教程并观看了很多关于这个主题的视频来尝试解决我的问题并且没有任何运气。我已经在下面的代码中编写了我从上次观看的视频中学到的所有碰撞检测代码。谁能告诉我我做错了什么。任何建议将不胜感激,谢谢。

//
//  GameScene.swift
//  Bird Flappy Game
//
//  Created by Brandon Ballard on 1/4/15.
//  Copyright (c) 2015 Brandon Ballard. All rights reserved.
//

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    var bird = SKSpriteNode()
    var pipeUpTexture = SKTexture()
    var pipeDownTexture = SKTexture()
    var pipesMoveAndRemove = SKAction()

    let pipeGap = 150.0

    enum ColliderType:UInt32 {
        case BIRD = 1
        case PIPE = 2
    }

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */


        backgroundColor = SKColor.cyanColor()

        //physics
        self.physicsWorld.gravity = CGVectorMake(0.0, -15.0);
        self.physicsWorld.contactDelegate = self

        func didBeginContact(contact: SKPhysicsContactDelegate) {
            scene?.view?.paused = true
            bird.setScale(12.0)
        }


        //Bird
        var birdTexture = SKTexture(imageNamed:"Bird")
        birdTexture.filteringMode = SKTextureFilteringMode.Nearest

        bird = SKSpriteNode(texture: birdTexture)
        bird.setScale(0.6)
        bird.position = CGPoint(x: 375, y: self.frame.size.height * 0.6)

        bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height / 2.0)
        bird.physicsBody?.dynamic = true
        bird.physicsBody?.allowsRotation = true
        bird.physicsBody?.affectedByGravity = true
        bird.physicsBody!.categoryBitMask = ColliderType.BIRD.rawValue
        bird.physicsBody!.contactTestBitMask = ColliderType.PIPE.rawValue
        bird.physicsBody!.collisionBitMask = ColliderType.PIPE.rawValue

        self.addChild(bird)

        //Ground
        var groundTexture = SKTexture(imageNamed: "Ground")

        var sprite = SKSpriteNode(texture: groundTexture)
        sprite.setScale(2.0)
        sprite.position = CGPointMake(self.size.width / 2, sprite.size.height / 2.0)


        self.addChild(sprite)

        var ground = SKNode()

        ground.position = CGPointMake(0, groundTexture.size().height + 0)
        ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width,     groundTexture.size().height * 2.0))

        ground.physicsBody?.dynamic = false
        self.addChild(ground)



        //Pipes

        //Create the Pipes

        pipeUpTexture = SKTexture(imageNamed: "PipeUp")
        pipeDownTexture = SKTexture(imageNamed: "PipeDown")

        //Movement of Pipes

        let distanceToMove = CGFloat(self.frame.size.width + 2.0 * pipeUpTexture.size().width)
        let movePipes = SKAction.moveByX(-distanceToMove, y: 0.0, duration: NSTimeInterval(0.01 * distanceToMove))
        let removePipes = SKAction.removeFromParent()

        pipesMoveAndRemove = SKAction.sequence([movePipes,removePipes])

        //Spawn Pipes

        let spawn = SKAction.runBlock({() in self.spawnPipes()})
        let delay = SKAction.waitForDuration(NSTimeInterval(2.0))
        let spawnThenDelay = SKAction.sequence([spawn,delay])
        let spawnThenDelayForever = SKAction.repeatActionForever(spawnThenDelay)

        self.runAction(spawnThenDelayForever)
    }

    func spawnPipes() {

        let pipePair = SKNode()
        pipePair.position = CGPointMake(self.frame.size.width + pipeUpTexture.size().width * 2, 0)
        pipePair.zPosition = -10

        let height = UInt32(self.frame.size.height / 4)
        let y = arc4random() % height + height

        var pipeDown = SKSpriteNode(texture: pipeDownTexture)
        pipeDown.setScale(2.0)////////
        pipeDown.position = CGPointMake(3.0, CGFloat(y) + pipeDown.size.height + CGFloat(pipeGap) )

        pipeDown.physicsBody = SKPhysicsBody(rectangleOfSize: pipeDown.size)
        pipeDown.physicsBody?.dynamic = false
        pipeDown.physicsBody!.affectedByGravity = false
        pipeDown.physicsBody!.categoryBitMask = ColliderType.PIPE.rawValue
        pipeDown.physicsBody!.contactTestBitMask = ColliderType.BIRD.rawValue
        pipeDown.physicsBody!.collisionBitMask = ColliderType.BIRD.rawValue
        pipePair.addChild(pipeDown)

        var pipeUp = SKSpriteNode(texture: pipeUpTexture)
        pipeUp.setScale(2.0)
        pipeUp.position = CGPointMake(0.0, CGFloat(y))

        pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size )
        pipeUp.physicsBody?.dynamic = false
        pipeUp.physicsBody!.affectedByGravity = false
        pipeUp.physicsBody!.categoryBitMask = ColliderType.PIPE.rawValue
        pipeUp.physicsBody!.contactTestBitMask = ColliderType.BIRD.rawValue
        pipeUp.physicsBody!.collisionBitMask = ColliderType.BIRD.rawValue
        pipePair.addChild(pipeUp)

        pipePair.runAction(pipesMoveAndRemove)
        self.addChild(pipePair)

    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        /* Called when a touch begins */

        for touch: AnyObject in touches {



            let location = touch.locationInNode(self)

            bird.physicsBody?.velocity = CGVectorMake( 0, 0 )
            bird.physicsBody?.applyImpulse(CGVectorMake(0,25))



        }
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

您将 didBeginContact 放在 didMoveToView 的内部。它不能从那里调用。把它放在你的 class

的正文中

据我所知,您只需要检测碰撞,而不是实际模拟它们。为此,您只需设置 physicsBodies 的 contactTestBitMask。您可以将 collisionBitMask 设置为 0。

bird.physicsBody!.collisionBitMask = 0

pipe.physicsBody!.collisionBitMask = 0

另外,正如hamobi已经说过的,didBeginContact方法需要在带有override关键字的didMoveToView方法之外。 (这个 question 和你的问题完全一样)

class GameScene: SKScene, SKPhysicsContactDelegate {
    // ...
    override func didMoveToView(view: SKView) {
        self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)

        // set as delegate:
        self.physicsWorld.contactDelegate = self

        // ..
    }

    // should be called now
    func didBeginContact(contact: SKPhysicsContact){
        scene?.view?.paused = true
            bird.setScale(12.0)
    }
}