This is the setup
// Create a scene
scene = SKScene(size: self.view.frame.size)
let sceneHeight = scene.frame.height
let sceneWidth = scene.frame.width
// Create nodes
// Rectangle
let shapeWidth: CGFloat = 100
let shapeHeight = shapeWidth
let shapeNode = SKShapeNode(rect: CGRectMake(0, 0, shapeWidth, 100))
shapeNode.position = CGPoint(x: sceneWidth/2 - shapeWidth/2, y: 300)
shapeNode.fillColor = UIColor.redColor()
shapeNode.strokeColor = UIColor.redColor()
// Floor
let floorWidth: CGFloat = sceneWidth
let floorHeight: CGFloat = 10
let floorNode = SKShapeNode(rect: CGRectMake(0, 0, floorWidth, floorHeight))
floorNode.position = CGPoint(x: 0, y: 100)
floorNode.fillColor = UIColor.greenColor()
floorNode.strokeColor = UIColor.greenColor()
// Create the node tree
scene.addChild(floorNode)
scene.addChild(shapeNode)
Then I define and add two physics bodies to my two nodes.
// Create physics
let shapePhysicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: shapeWidth, height: shapeHeight))
shapePhysicsBody.dynamic = true
shapePhysicsBody.categoryBitMask = PhysicsCategory.Shape
shapePhysicsBody.contactTestBitMask = PhysicsCategory.Floor
shapePhysicsBody.collisionBitMask = PhysicsCategory.None
shapePhysicsBody.usesPreciseCollisionDetection = true
let floorPhysicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: floorWidth, height: floorHeight))
floorPhysicsBody.dynamic = true
floorPhysicsBody.categoryBitMask = PhysicsCategory.Floor
floorPhysicsBody.contactTestBitMask = PhysicsCategory.Shape
floorPhysicsBody.collisionBitMask = PhysicsCategory.None
floorPhysicsBody.usesPreciseCollisionDetection = true
floorPhysicsBody.affectedByGravity = false
// Add physics
shapeNode.physicsBody = shapePhysicsBody
floorNode.physicsBody = floorPhysicsBody
scene.physicsWorld.gravity = CGVector(dx: 0, dy: -1)
scene.physicsWorld.contactDelegate = self
This sort of works, that is the rectangle shape does fall from it's initial position and the collision delegate is called when a collision happens.
The contents of my didBeginContact:
method.
func didBeginContact(contact: SKPhysicsContact) {
var firstBody : SKPhysicsBody
var secondBody : SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if ((firstBody.categoryBitMask & PhysicsCategory.Floor != 0) && (secondBody.categoryBitMask & PhysicsCategory.Shape != 0)) {
secondBody.dynamic = false
println("collision")
}
}
But the shape node stops way before there's a visual contact. I hope these images give an impression of how that looks.
Starts here
This is where the contact happens
Why is there such a gap between them? What am I missing? I want them to visually touch each other before the rectangle stops moving.