Collisions between sprites in SpriteKit - ios

I'm making a game in XCode using SpriteKit. The game has a player and different types of projectiles that he has to avoid. When the player collides with the projectiles, the score changes and the projectile disappears. However, when two projectiles collide, they kind of bounce away.
I want to make that every time two projectiles collide, they act like nothing happened and they keep going in their original path. What should I do?
*Note: This is not the whole code, it's just what matters.
import SpriteKit
struct Physics {
static let player : UInt32 = 1
static let missileOne : UInt32 = 2
static let missileTwo : UInt32 = 3
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var player = SKSpriteNode(imageNamed: "p1.png")
override func didMoveToView(view: SKView) {
physicsWorld.contactDelegate = self
player.position = CGPointMake(self.size.width/2, self.size.height/5)
player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
player.physicsBody?.affectedByGravity = false
player.physicsBody?.dynamic = false
player.physicsBody?.categoryBitMask = Physics.player
player.physicsBody?.collisionBitMask = Physics.missileOne
player.physicsBody?.collisionBitMask = Physics.missileTwo
var missileOneTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("SpawnMissileOne"), userInfo: nil, repeats: true)
var missileTwoTimer = NSTimer.scheduledTimerWithTimeInterval(1.2, target: self, selector: Selector("SpawnMissileTwo"), userInfo: nil, repeats: true)
self.addChild(player)
}
//When contact happens
func didBeginContact(contact: SKPhysicsContact) {
var firstBody : SKPhysicsBody = contact.bodyA
var secondBody : SKPhysicsBody = contact.bodyB
if ((firstBody.categoryBitMask == Physics.player) && (secondBody.categoryBitMask == Physics.missileOne)) {
CollisionWithMissileOne(firstBody.node as SKSpriteNode, missileOne: secondBody.node as SKSpriteNode)
} else if ((firstBody.categoryBitMask == Physics.player) && (secondBody.categoryBitMask == Physics.missileTwo)){
CollisionWithMissileTwo(firstBody.node as SKSpriteNode, missileTwo: secondBody.node as SKSpriteNode)
} else if ((firstBody.categoryBitMask == Physics.missileOne)&&(secondBody.categoryBitMask == Physics.missileTwo)) {
CollisionBetweenMissiles(firstBody.node as SKSpriteNode, missileTwo: secondBody.node as SKSpriteNode)
}
}
//For Player and MissileOne
func CollisionWithMissileOne(player: SKSpriteNode, missileOne: SKSpriteNode) {
missileOne.removeFromParent()
}
//For Player and MissileTwo
func CollisionWithMissileOne(player: SKSpriteNode, missileTwo: SKSpriteNode) {
missileTwo.removeFromParent()
}
//For MissileOne and MissileTwo
func CollisionBetweenMissiles(missileOne: SKSpriteNode, missileTwo: SKSpriteNode) {
???WHAT SHOULD I CODE HERE???
}
}

The confusion is that the collisionBitMask is used to define which physicsBodies that interacts in the physicsModel. What you really want is contactTestBitmask.
Also your Physics doesn't return proper values to use for a Bit Mask. As pure Ints they should be 1,2,4,8 etc.
Here is your code changed to something that (hopefully) works, I've commented changes wherever I've made them.
struct Physics {
static let player : UInt32 = 1
static let missileOne : UInt32 = 2
static let missileTwo : UInt32 = 4 // to work properly as bit masks
}
This change is necessary if you want to check for contact with more than one type of physicsBody.categoryBitMask. Check out the player.physicsBody?.contactTestBitMask = ... in didMoveToView:
override func didMoveToView(view: SKView) {
physicsWorld.contactDelegate = self
// All your existing player-stuff is fine until...
// contactTest, not collision but contact, also: use bitwise OR
player.physicsBody?.contactTestBitMask = Physics.missileOne | Physics.missileTwo
self.addChild(player)
// It is not recommended to use NSTimer for SpriteKit, use SKActions instead
let missileOneWait = SKAction.waitForDuration(1)
let callSpawnOneAction = SKAction.runBlock({ self.spawnMissileOne() })
let missileOneRepeat = SKAction.repeatActionForever(SKAction.sequence([missileOneWait, callSpawnOneAction]))
runAction(missileOneRepeat)
let missileTwoWait = SKAction.waitForDuration(1.2)
let callSpawnTwoAction = SKAction.runBlock({ self.spawnMissileTwo() })
let missileTwoRepeat = SKAction.repeatActionForever(SKAction.sequence([missileTwoWait, callSpawnTwoAction]))
runAction(missileTwoRepeat)
}
Pretty much rewritten didBeginContact to something I believe reads and scales a lot better:
func didBeginContact(contact: SKPhysicsContact) {
var firstBody = contact.bodyA
var secondBody = contact.bodyB
// Rewritten with dynamic variables
var playerNode : SKSpriteNode? {
if firstBody.categoryBitMask == Physics.player {
return firstBody.node as? SKSpriteNode
} else if secondBody.categoryBitMask == Physics.player {
return secondBody.node as? SKSpriteNode
}
return nil
}
// If you want to handle contact between missiles you need to split this
// into two different variables
var missileNode : SKSpriteNode? {
let bitmask1 = firstBody.categoryBitMask
let bitmask2 = secondBody.categoryBitMask
if bitmask1 == Physics.missileOne || bitmask1 == Physics.missileTwo {
return firstBody.node as? SKSpriteNode
} else if bitmask2 == Physics.missileOne || bitmask2 == Physics.missileTwo {
return secondBody.node as? SKSpriteNode
}
return nil
}
if playerNode != nil {
collisionBetweenPlayer(playerNode, missile: missileNode)
}
}
Then you'll only need one function for contact between missile and player:
func collisionBetweenPlayer(player: SKSpriteNode?, missile: SKSpriteNode?) {
missile?.removeFromParent()
}

Related

swift spritekit how to run an action with a specified duration?

I'm trying to make my player change image once it detects collision with one of my game items and changes back after 0.3 seconds however, I dont know how to set the 0.3 duration for my image change? Currently the image changes in a flash
Here's my code:
func didBegin(_ contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if firstBody.node?.name == "Player" && secondBody.node?.name == "Poop" {
let sound = SKAction.playSoundFileNamed("coinsound", waitForCompletion: false)
run(sound)
score += 1
// Changes's player image to Poop once it collides with "Poop"
let poopImage = SKTexture(imageNamed: "Poop")
let action = SKAction.setTexture(poopImage)
firstBody.node?.run(action)
scoreLabel?.text = String(score)
secondBody.node?.removeFromParent()
}
}
// Changes player's image back to what it was once it starts moving
private func managePlayer(){
if canMove{
player?.move(left: moveLeft)
player?.texture = SKTexture(imageNamed:"Player")
}
}
Thank you for your help in advance
Inside didBegin(_ contact) put your actions in a sequence like this
let sequence = SKAction.sequence([firstTextureChangeAction, SKAction.wait(forDuration:0.3), secondTextureChangeAction])
firstBody.node?.run(sequence)

How to detect different types of collisions in SpriteKit

I have two different types of collisions I want to detect in SpriteKit:
When ballOne hits goalOne and when ballTwo hits goalTwo:
So far I've added my different physics categories:
struct physicsCategory {
static let ballOne :UInt32 = 0x1 << 0
static let goalOne :UInt32 = 0x1 << 1
static let ballTwo :UInt32 = 0x1 << 2
static let goalTwo :UInt32 = 0x1 << 3
}
And here's the relevant parts of my class:
class gameScene: SKScene, SKPhysicsContactDelegate {
var borderBody:SKPhysicsBody!
var myscore:Int = 0
var opponentScore:Int = 10
override func sceneDidLoad() {
super.sceneDidLoad()
physicsWorld.contactDelegate = self
}
func didBegin(_ contact: SKPhysicsContact) {
let firstBody = contact.bodyA.node as! SKSpriteNode
let secondBody = contact.bodyB.node as! SKSpriteNode
if ((firstBody.name == "ballOne") && (secondBody.name == "goalOne")) {
collisionGoalOne(BallOne: firstBody, GoalOne: secondBody)
}
else {
}
}
func collisionGoalOne(BallOne: SKSpriteNode, GoalOne: SKSpriteNode) {
addScore()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let touchLocation = touch!.location(in: self)
let ballOne = childNode(withName: "ballOne") as! SKSpriteNode
ballOne.physicsBody?.categoryBitMask = physicsCategory.ballOne
ballOne.physicsBody?.collisionBitMask = physicsCategory.goalOne
ballOne.physicsBody?.contactTestBitMask = physicsCategory.goalOne
ballOne.physicsBody?.isDynamic = true
let goalOne = childNode(withName: "goalOne") as! SKSpriteNode
goalOne.physicsBody?.categoryBitMask = physicsCategory.goalOne
goalOne.physicsBody?.collisionBitMask = physicsCategory.ballOne
goalOne.physicsBody?.contactTestBitMask = physicsCategory.ballOne
goalOne.physicsBody?.isDynamic = false
}
}
Right now the app crashes when the ball collides with the wall on
let firstBody = contact.bodyA.node as! SKSpriteNode
with "Could not cast value of type 'appName.gameScene' (0x105320) to 'SKSpriteNode' (0x1877b5c)."
Would love to understand why this crash is happening and if this is even a good approach to collision handling. Thank you.
FirstBody might not be able to be cast to SKSpriteNode, so only create that variable after you check which nodes collide.
Note that ballOne could be either bodyA or bodyB so change your code to check for both possibilities.
I changed your code a bit. Hope this helps
if ((contact.bodyA.node?.name == "ballOne") && (contact.bodyB.node?.name == "goalOne")) {
let firstBody = contact.bodyA.node as! SKSpriteNode
let secondBody = contact.bodyB.node as! SKSpriteNode
collisionGoalOne(BallOne: firstBody, GoalOne: secondBody)
} else if ((contact.bodyA.node?.name == "goalOne") && (contact.bodyB.node?.name == "ballOne")) {
let firstBody = contact.bodyA.node as! SKSpriteNode
let secondBody = contact.bodyB.node as! SKSpriteNode
collisionGoalOne(BallOne: secondBody, GoalOne: firstBody)
}
I think there are a couple of changes you might want to make.
When your ball node contacts the wall, I believe your didBegin(_ contact: SKPhysicsContact) method is invoked with one body as the ball (SKNode) and the other body as the scene border (SKScene).
Forcing a cast of SKScene to SKSpriteNode with let firstBody = contact.bodyA.node as! SKSpriteNode crashes, as RT5754 points out.
To fix this you might consider the following:
Add a physics category for the wall/border. Something like:
static let sceneBorder :UInt32 = 0x1 << 4
Update the border and the ball nodes to have collision physics:
ballNode.physicsBody?.collisionBitMask = physicsCategory.sceneBorder
borderNode.physicsBody?.collisionBitMask = physicsCategory.ballOne + physicsCategory.ballTwo
When handling other contact logic, my pattern for
didBegin(_ contact: SKPhysicsContact)
is like this:
func didBegin(_ contact: SKPhysicsContact) {
var firstBody: SKPhysicsBody = contact.bodyA
var secondBody: SKPhysicsBody = contact.bodyB
//in did begin contact, order the bodies by physics category
if firstBody.categoryBitMask > secondBody.categoryBitMask {
let temp = secondBody
secondBody = firstBody
firstBody = temp
}
//logic to handle contact is based on physicsCategory
if secondBody.categoryBitMask == physicsCategory.whatever {
methodToHandleWhatever(thingOne: firstBody, thingTwo: secondBody)
}

didBeginContact() called without contact

I have a game that is ready to publish, but my fiancé who is still on iOS 8.1 had this issue. It's fine with iOS 9 but I recreated the problem on the simulator with iOS 8.1.
When I click start game and the scene is loaded, enemies begin to appear at the edges of the screen. They use actions to push them to the other edge of the screen and then they are removed from their parent. Only, didBeginContact() is called as soon as they are added to the screen.
struct PhysicsCategory {
static let None : UInt32 = 0
static let All : UInt32 = UInt32.max
static let fishy : UInt32 = 0b1 // 1
static let enemy : UInt32 = 0b10 // 2
static let powerup : UInt32 = 0b11 // 3
}
Good guy (fishy) set up and movement)
fishy.physicsBody = SKPhysicsBody(texture:fishy.texture!, size:fishy.size)
fishy.physicsBody?.dynamic = true
fishy.physicsBody?.categoryBitMask = PhysicsCategory.fishy
fishy.physicsBody?.contactTestBitMask = PhysicsCategory.enemy
fishy.physicsBody?.collisionBitMask = PhysicsCategory.None
fishy.physicsBody?.usesPreciseCollisionDetection = true
Enemy set up and movement
enemy.physicsBody = SKPhysicsBody(texture:enemy.texture!, size:enemy.size)
enemy.physicsBody?.dynamic = true // 2
enemy.physicsBody?.categoryBitMask = PhysicsCategory.enemy // 3
enemy.physicsBody?.contactTestBitMask = PhysicsCategory.fishy // 4
enemy.physicsBody?.collisionBitMask = PhysicsCategory.None // 5
self.addChild(enemy)
let action1 = SKAction.rotateToAngle(angle, duration: 0.0, shortestUnitArc: true)
let action = SKAction.moveTo(finishPos,duration:Double(random(min: 5,max: 13)))
let action2 = SKAction.removeFromParent()
let sequence = SKAction.sequence([action1,action,action2])
enemy.runAction(sequence)
This is called for most of the enemy nodes that are added, but not all. I only want it called when they contact, but it is running at their creation. (It calls even when the path of the enemy is not in contact with the fishy)
func didBeginContact(contact: SKPhysicsContact) {
var enemyContact: SKPhysicsBody
var fishyContact: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
fishyContact = contact.bodyA
enemyContact = contact.bodyB
} else {
fishyContact = contact.bodyB
enemyContact = contact.bodyA
}
if ((enemyContact.categoryBitMask & PhysicsCategory.enemy != 0) && (fishyContact.categoryBitMask & PhysicsCategory.fishy != 0)) {
if (enemyContact.node != nil && fishyContact.node != nil) {
projectileDidCollide(fishyContact.node as! SKSpriteNode, badGuy:enemyContact.node as! SKSpriteNode)
}
}
}
Again, this doesn't occur in iOS 9.0 and above. Thanks in advance.

Simplifying collision and player death in SpriteKit

I want to add a bunch of different rocks and other dangerous objects that the player can collide with and die. How would I do this effectively? Now if I would copy paste these functions, it would surely work. But it seems like a huge amount of unnecessary code.
Sidenote: I'm very new to xcode, swift 2 & Sprite-kit.
func didBeginContact(contact: SKPhysicsContact) {
let firstBody : SKPhysicsBody = contact.bodyA
let secondBody : SKPhysicsBody = contact.bodyB
if ((firstBody.categoryBitMask == PhysicsCategory.Rock) && (secondBody.categoryBitMask == PhysicsCategory.Bullet) || (firstBody.categoryBitMask == PhysicsCategory.Bullet) && (secondBody.categoryBitMask == PhysicsCategory.Rock)) {
CollisionWithBullet(firstBody.node as! SKSpriteNode, Bullet: secondBody.node as! SKSpriteNode)
}
if ((firstBody.categoryBitMask == PhysicsCategory.Rock) && (secondBody.categoryBitMask == PhysicsCategory.Player) || (firstBody.categoryBitMask == PhysicsCategory.Player) && (secondBody.categoryBitMask == PhysicsCategory.Rock)) {
CollisionWithPlayer(firstBody.node as! SKSpriteNode, Player: secondBody.node as! SKSpriteNode)
}
}
func CollisionWithPlayer(Rock: SKSpriteNode, Player: SKSpriteNode){
let ScoreDefault = NSUserDefaults.standardUserDefaults()
ScoreDefault.setValue(Score, forKey: "Score")
ScoreDefault.synchronize()
let HighscoreDefault = NSUserDefaults.standardUserDefaults()
if (HighscoreDefault.valueForKey("Highscore") != nil){
Highscore = HighscoreDefault.valueForKey("Highscore") as! NSInteger
} else {
Highscore = 0
}
if (Score > Highscore){
let HighscoreDefault = NSUserDefaults.standardUserDefaults()
HighscoreDefault.setValue(Score, forKey: "Highscore")
}
self.view?.presentScene(EndScene())
ScoreLabel.removeFromSuperview()
}
So what you're likely looking for here is the bitwise OR operator and the bitwise AND operator.
With SpriteKit, physicsBodies can have multiple categories assigned to them. For instance, if we have the following categories set up:
enum CollisionCategories : UInt32 {
case Player = 1
case Enemy = 2
case Rock = 4
case Bullet = 8
}
we can set up the player category and contact bitmasks as follows:
let player = SKSpriteNode(color: UIColor.blackColor(), size: CGSize(width: 50, height: 50))
player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
player.physicsBody?.categoryBitMask = CollisionCategories.Player.rawValue
player.physicsBody?.contactTestBitMask = CollisionCategories.Enemy.rawValue
and two enemy category and contact bitmasks as follows:
let rockEnemy = SKSpriteNode(color: UIColor.greenColor(), size: CGSize(width: 25, height: 25))
rockEnemy.physicsBody = SKPhysicsBody(rectangleOfSize: rockEnemy.size)
rockEnemy.physicsBody?.categoryBitMask = CollisionCategories.Enemy.rawValue | CollisionCategories.Rock.rawValue
rockEnemy.physicsBody?.contactTestBitMask = CollisionCategories.Player.rawValue
let bulletEnemy = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 25, height: 25))
bulletEnemy.physicsBody = SKPhysicsBody(rectangleOfSize: bulletEnemy.size)
bulletEnemy.physicsBody?.categoryBitMask = CollisionCategories.Enemy.rawValue | CollisionCategories.Bullet.rawValue
bulletEnemy.physicsBody?.contactTestBitMask = CollisionCategories.Player.rawValue
Notice that on setting the category bitmasks, I am using the bitwise OR operator ('|'). This is a nice way of setting the bitmasks to two different categories at the same time. This way, a sprite can be both a rock and an enemy or a bullet and an enemy, etc.
See the image below for an idea of what is happening bitwise under the hood.
In our contact detection function, we can use the bitwise AND operator ('&') to see if our contact possesses a certain category.
func didBeginContact(contact: SKPhysicsContact) {
let firstBody : SKPhysicsBody = contact.bodyA
let secondBody : SKPhysicsBody = contact.bodyB
if (firstBody.categoryBitMask & CollisionCategories.Player.rawValue == CollisionCategories.Player.rawValue &&
secondBody.categoryBitMask & CollisionCategories.Enemy.rawValue == CollisionCategories.Enemy.rawValue) {
print("The collision was between the Player and an Enemy")
}
else if (firstBody.categoryBitMask & CollisionCategories.Enemy.rawValue == CollisionCategories.Enemy.rawValue &&
secondBody.categoryBitMask & CollisionCategories.Player.rawValue == CollisionCategories.Player.rawValue) {
print("The collision was between the Player and an Enemy")
}
}
This way, you can have enemies with multiple categories, but you can always do one check to see if a node is in fact an enemy, regardless of what other categories they might possess.

didBeginContact for three sprites works for 2 sprites, but not for the third one - Swift2

I have a bird, multiple desks and a star. When the bird collides with one of the desks, the didBeginContact method works fine, but when it collides with the star, nothing happens. I will copy the code where I added some print statements so it is easier to see what is happening and then I will paste the print statements that it prints out.
Bird (just the initialization of the physicsBody part):
class Bird: SKSpriteNode {
var sc: SKScene!
init(sc: SKScene) {
let texture = SKTexture(imageNamed: "hero")
let size = texture.size()
self.sc = sc
super.init(texture: texture, color: UIColor.clearColor(), size: CGSizeMake(size.width/2, size.height/2))
self.zPosition = Layer.Bird.rawValue
self.name = "bird"
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width/2)
self.physicsBody?.categoryBitMask = PhysicsCategory.Bird
self.physicsBody?.collisionBitMask = PhysicsCategory.Desk
self.physicsBody?.contactTestBitMask = PhysicsCategory.Desk | PhysicsCategory.StarSpecial | PhysicsCategory.Star
self.physicsBody?.allowsRotation = true
self.physicsBody?.restitution = 0
self.physicsBody?.usesPreciseCollisionDetection = true
}
// other methods and the required init
}
The star class is constructed the same way so I will just copy physicsBody related code:
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width/2, center: self.position)
self.physicsBody?.affectedByGravity = false
self.physicsBody?.pinned = true
self.physicsBody?.categoryBitMask = PhysicsCategory.StarSpecial
self.physicsBody?.collisionBitMask = PhysicsCategory.None
self.physicsBody?.contactTestBitMask = PhysicsCategory.Bird
self.physicsBody?.usesPreciseCollisionDetection = true
self.physicsBody?.allowsRotation = false
self.physicsBody?.restitution = 0
self.physicsBody?.usesPreciseCollisionDetection = true
And the didBeginContact method in GameScene:
func didBeginContact(contact: SKPhysicsContact) {
print("something has collided")
if contact.bodyA.categoryBitMask == PhysicsCategory.Bird && contact.bodyB.categoryBitMask == PhysicsCategory.Desk {
birdSprite.BirdDidCollideWithDesk(contact.bodyA.node as! Bird, desk: contact.bodyB.node as! Desk, scoreClass: scoreClass, scoreLabel: scoreLabel)
print("bird and desk have collided")
} else if contact.bodyA.categoryBitMask == PhysicsCategory.Desk && contact.bodyB.categoryBitMask == PhysicsCategory.Bird {
print("desk and bird have collided")
birdSprite.BirdDidCollideWithDesk(contact.bodyB.node as! Bird, desk: contact.bodyA.node as! Desk, scoreClass: scoreClass, scoreLabel: scoreLabel)
}
if contact.bodyA.categoryBitMask == PhysicsCategory.Bird && contact.bodyB.categoryBitMask == PhysicsCategory.StarSpecial {
print("collided into star1")
starSpecial.removeStar(contact.bodyB.node as! Star)
} else if contact.bodyA.categoryBitMask == PhysicsCategory.StarSpecial && contact.bodyB.categoryBitMask == PhysicsCategory.Bird {
print("collided into star2")
starSpecial.removeStar(contact.bodyB.node as! Star)
}
}
If I run it, I get the following messages:
If the bird collides with a desk: "something has collided", "desk and bird have collided"
If the bird collides with the star: "something has collided"
Neither of second two conditions is met, so the message "collided into star1" or "collided into star2" is not printed out.
Any idea what could be causing this?

Resources