SpriteKit physics false positive?

徘徊边缘 提交于 2020-02-06 05:50:47

问题


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...

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)
}

}

来源:https://stackoverflow.com/questions/29763240/spritekit-physics-false-positive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!