1

I am trying to make an explosion occur when the Player and the Enemy collide. At the moment I am having problems with detecting the collision between the Player and the Enemy. I have tried various different ways and looked at various different articles but haven't quite managed to fix the problem. Below is the code that I am using at the moment:

Player Class:

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        
    }

    ... 
}

Game Scene Class:

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!
    }

    ...
}
Anh Pham
  • 2,108
  • 9
  • 18
  • 29
Yes
  • 43
  • 4
  • 1) We don't know anything about PLAYER. 2) Your SKPhysicsContact didBegin suggests that the game can crash. – El Tomato Aug 03 '17 at 00:50

0 Answers0