Swift 3中的碰撞检测

时间:2017-08-02 22:55:49

标签: swift sprite-kit physics collision

当玩家和敌人发生碰撞时,我试图让爆炸发生。目前我在检测玩家和敌人之间的碰撞时遇到了问题。我尝试了各种不同的方式,看了各种不同的文章,但还没有完全解决问题。以下是我目前使用的代码:

玩家等级:

class Player: SKSpriteNode {

    func initializePlayer() {
        physicsBody = SKPhysicsBody(circleOfRadius: size.height/2)
        physicsBody?.affectedByGravity = false;
        physicsBody?.isDynamic = false;
        physicsBody?.categoryBitMask = ColliderType.PLAYER
        physicsBody?.contactTestBitMask = ColliderType.ENEMY        
    }

    ... 
}

游戏场景类:

import SpriteKit
import UIKit

struct ColliderType {

    static let PLAYER: UInt32 = 0x1 << 0;
    static let ENEMY: UInt32 = 0x1 << 1;
}

class GamePlayScene: SKScene, SKPhysicsContactDelegate {

    private var player: Player?;
    ...

    override func didMove(to view: SKView) {
        physicsWorld.contactDelegate = self;

        initializeGame();

        _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: 
    #selector(SpawnEnemies), userInfo: nil, repeats: true)        
    }

    ...

    func SpawnEnemies() {
        let enemy = SKSpriteNode(imageNamed: "Enemy.png")
        enemy.setScale(1.5)
        let Pos = randomBetweenNumbers(firstNum: -enemy.size.height, secondNum: frame.height - enemy.size.height/4)

        enemy.position = CGPoint(x: self.size.width, y: CGFloat(Pos))
        enemy.zPosition = 2;
        enemy.physicsBody = SKPhysicsBody(circleOfRadius: enemy.size.height/2)
        enemy.physicsBody?.affectedByGravity = false
        enemy.physicsBody?.categoryBitMask = ColliderType.ENEMY
        enemy.physicsBody?.contactTestBitMask = ColliderType.PLAYER

        ...
    }

    func didBegin(_ contact: SKPhysicsContact) {
        var body1 = SKPhysicsBody()
        var body2 = SKPhysicsBody()

        body1 = contact.bodyA
        body2 = contact.bodyB

        if body1.categoryBitMask == ColliderType.PLAYER && body2.categoryBitMask == ColliderType.ENEMY {
            // if the player has hit the enemy

            body2.node?.removeFromParent()
            spawnExplosion(Pos: body1.node!.position)            
        }  
    }

    ...

    private func initializeGame() {
        player = childNode(withName: "Player") as? Player!
    }

    ...
}

0 个答案:

没有答案