Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Sprite Collision without bouncing off in SpriteKit

I am new to coding with SpriteKit / Swift and have the following problem: A character is supposed to collect coins by jumping into them. There is no problem in detecting the collision and getting rid of the collected coin but my character bounces of the coin before it disappears.

The character is supposed to fly through the coin and collect it on the way.

let playerCategory: UInt32 = 0x1 << 0
let coinCategory: UInt32 = 0x1 << 1

player = SKSpriteNode(texture: playerTexture)
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.height / 2)
player.physicsBody?.dynamic = true
player.physicsBody?.allowsRotation = false
player.physicsBody?.categoryBitMask = playerCategory
player.physicsBody?.contactTestBitMask = coinCategory

var coin:SKSpriteNode = SKSpriteNode(texture: coinTexture)
coin.physicsBody = SKPhysicsBody(circleOfRadius: coin.size.height / 2)
coin.physicsBody?.dynamic = false
coin.physicsBody?.allowsRotation = false
coin.physicsBody?.categoryBitMask = coinCategory
coin.physicsBody?.contactTestBitMask = playerCategory

func playerDidCollideWithCoin(player:SKSpriteNode, thisCoin:SKSpriteNode) {
    thisCoin.removeFromParent()
    coinsCollected++
}

Collision detection works fine like this but as I said, how can I avoid the bumping of and replace it with a "flying through"?

I'm using Xcode 6 Beta 7

Thanks in advance!

Solution in the comment below ;)

like image 740
MikeB Avatar asked Sep 04 '14 14:09

MikeB


1 Answers

Thee default behavior of spritekit is that everything collides with everything unless the Collision bit mask is change to 0.

Change this value in your code to 0 in all those objects that you do not want to bounce off but receive notifications from them.

player = SKSpriteNode(texture: playerTexture)
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.height / 2)
player.physicsBody?.dynamic = true
player.physicsBody?.allowsRotation = false
player.physicsBody?.categoryBitMask = playerCategory
player.physicsBody?.contactTestBitMask = coinCategory
player.physicsBody?.collisionBitMask = 0

var coin:SKSpriteNode = SKSpriteNode(texture: coinTexture)
coin.physicsBody = SKPhysicsBody(circleOfRadius: coin.size.height / 2)
coin.physicsBody?.dynamic = false
coin.physicsBody?.allowsRotation = false
coin.physicsBody?.categoryBitMask = coinCategory
coin.physicsBody?.contactTestBitMask = playerCategory
coin.physicsBody?.collisionBitMask = 0

This will stop those objects from bouncing against each other.

like image 133
Jprens Avatar answered Sep 28 '22 23:09

Jprens