I have a question: I have followed the instructions from video "Bring on the enemies: Timer, linearDamping, angularDamping" and after multiple failures (even I copied and pasted the code given in the lessons) my spaceship does not collision against the enemies (basket ball, hammers and tvs). It could be that Xcode has been updated and the missing code (or the different code) does not appear on the video?
How can I make my objects to collide between them? Thanks in advance for your help.
My code:
import SpriteKit
class GameScene: SKScene {
// MARK: - Elements in screen
var starfield: SKEmitterNode!
var player: SKSpriteNode!
var scoreLabel: SKLabelNode!
// MARK: - Constants and variables
var score = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
let possibleEnemies = ["ball", "hammer", "tv"]
var isGameOver: Bool = false
var gameTimer: Timer?
// MARK: - didMove()
override func didMove(to view: SKView) {
loadNodes()
}
// MARK: - Load Nodes method
func loadNodes() {
backgroundColor = .black
starfield = SKEmitterNode(fileNamed: "starfield")!
starfield.position = CGPoint(x: 1024, y: 384)
starfield.advanceSimulationTime(10)
addChild(starfield)
starfield.zPosition = -1
player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 100, y: 384)
player.physicsBody = SKPhysicsBody(texture: player.texture!, size: player.size)
player.physicsBody?.contactTestBitMask = 1 // Allows collision with other objects
addChild(player)
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.position = CGPoint(x: 16, y: 16)
scoreLabel.horizontalAlignmentMode = .left
addChild(scoreLabel)
score = 0
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
gameTimer = Timer.scheduledTimer(timeInterval: 0.35, target: self, selector: #selector(createEnemy), userInfo: nil, repeats: true)
}
@objc func createEnemy() {
guard let enemy = possibleEnemies.randomElement() else { return }
let sprite = SKSpriteNode(imageNamed: enemy)
sprite.position = CGPoint(x: 1200, y: Int.random(in: 50...736))
addChild(sprite)
sprite.physicsBody = SKPhysicsBody(texture: sprite.texture!, size: sprite.size)
sprite.physicsBody?.categoryBitMask = 1
sprite.physicsBody?.velocity = CGVector(dx: -500, dy: 0) // starts movement from right to left at a constant speed of 500
sprite.physicsBody?.angularVelocity = 5 // Spin in the air
sprite.physicsBody?.linearDamping = 0 // Related to air friction. Since we're in space, it is 0. How fast things slow down over time
sprite.physicsBody?.angularDamping = 0 // Related to air friction. Never stops spinning
}
// MARK: - update method
override func update(_ currentTime: TimeInterval) {
}
}
// MARK: - Extension: SKPhysicsContactDelegate
extension GameScene: SKPhysicsContactDelegate {
}