Reputation: 2928
I'm trying to build my first iOS swift game and I have some trouble in detection the collision between objects. I have some objects falling down, and another object on the bottom of the screen. I want to know when the falling objects touches the other object. So, here is what I have:
In my scene class (inside my init method):
player = SKSpriteNode(imageNamed: "playerImg")
player.position = CGPointMake(gameBoard.size.width/2, -(gameBoard.size.height + 55))
player.size = CGSize(width: 40,height: 40)
player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
player.physicsBody?.dynamic = false
player.physicsBody?.categoryBitMask = BodyType.bro.rawValue
player.physicsBody?.contactTestBitMask = BodyType.bro.rawValue
player.physicsBody?.affectedByGravity = true
In anther custom method I have (still in the same scene class):
let sprite = SKSpriteNode(texture: texture)
sprite.position = pointForColumn(block.column, row: block.row - 2)
block.sprite = sprite
sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
sprite.physicsBody?.dynamic = false
sprite.physicsBody?.categoryBitMask = BodyType.bro.rawValue
sprite.physicsBody?.contactTestBitMask = BodyType.bro.rawValue
sprite.physicsBody?.affectedByGravity = true
Here is my BodyType enum:
enum BodyType:UInt32 {
case bro = 1
case ground = 2
case anotherBody1 = 4
case anotherBody2 = 8
case anotherBody3 = 16
}
And finally, inside my didMoveToView method I have:
physicsWorld.contactDelegate = self
view.showsPhysics = true
So, I see the green border around my objects, but when they touch I have nothing inside the didBeginContact method (here attached a screenshot). Anyone, some idea about what is missing in order to have a trigger when collision detected ?
Upvotes: 0
Views: 1374
Reputation: 2928
I got it. I had to put
sprite.physicsBody?.dynamic = true
sprite.physicsBody?.affectedByGravity = false
and after that it works like a charm.
Upvotes: 1
Reputation: 126117
You're setting the contactTestBitMask
, not the collisionBitMask
. The former just makes SpriteKit notify you of contacts between bodies, but doesn't change anything in the physics simulation on contact. You need the latter for a contact to turn into a collision (and for the collision to be resolved, making the bodies stop or bounce off one another).
Upvotes: 0