1

The contact point provided by didBeginContact does not always rest in the paths that define the physics bodies involved in the collision. This behavior is most problematic in cases where the bodies never come into contact (if the circle node is 1px further right, the contact still happens though it is mathematically impossible.)

In the image and program below, the rectangle has a width of 100px, but the contact point (shown in the output) is at 101.4550...

Program results

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {


var node1:SKShapeNode
var node2:SKShapeNode
var node2PhysicsPath:CGPath
var contactPoint:SKShapeNode


required init?(coder aDecoder: NSCoder) {

    contactPoint = SKShapeNode(circleOfRadius: 10)
    contactPoint.strokeColor = SKColor(calibratedRed: 1, green: 0, blue: 0, alpha: 1)

    node1 = SKShapeNode()
    node1.position.x = 150
    node1.position.y = 200
    node1.physicsBody = SKPhysicsBody(circleOfRadius: 50)
    node1.physicsBody?.contactTestBitMask = 0xffffffff
    node1.physicsBody?.categoryBitMask = 0xffffffff
    node1.physicsBody?.usesPreciseCollisionDetection = true


    node2PhysicsPath = CGPathCreateWithRect(CGRect(x: 0, y: 0, width: 100, height: 100), nil)

    node2 = SKShapeNode()
    node2.physicsBody = SKPhysicsBody(polygonFromPath: node2PhysicsPath)
    node2.physicsBody?.dynamic = false
    node2.physicsBody?.contactTestBitMask = 0xffffffff
    node2.physicsBody?.categoryBitMask = 0xffffffff
    node2.physicsBody?.usesPreciseCollisionDetection = true

    super.init(coder: aDecoder)

    physicsWorld.contactDelegate = self
}

func didBeginContact(contact:SKPhysicsContact){
    println(contact.contactPoint);
    contactPoint.position = contact.contactPoint
    self.physicsWorld.speed = 0
    println(CGPathContainsPoint(node2PhysicsPath, nil, contact.contactPoint, true))
}

override func didMoveToView(view: SKView) {
    self.addChild(node1)
    self.addChild(node2)
    self.addChild(contactPoint)
    self.physicsWorld.gravity = CGVector(dx: 0, dy: -1.0)
}

}
Ian
  • 592
  • 5
  • 21

0 Answers0