我目前正在尝试在 SpriteKit 中实现先前生成的 SpriteNodes 从用户绘制的线反弹。为此,我需要给它们一个物理体,以便物体可以碰撞。有谁知道如何实现这个?非常感谢!
这是代码块:
-- 更新:问题解决了!这个问题中的工作代码。--
func createLine() {
let path = CGMutablePath()
path.move(to: pathArray[0])
for point in pathArray {
path.addLine(to: point)
}
let line = SKShapeNode()
line.path = path
line.fillColor = .clear
line.lineWidth = 1
line.zPosition = 3
line.strokeColor = .cyan
line.lineCap = .round
line.glowWidth = 20
line.physicsBody = SKPhysicsBody(polygonFrom: path)
line.physicsBody?.affectedByGravity = false
line.physicsBody?.isDynamic = true
line.physicsBody?.categoryBitMask = CollisionTypes.line.rawValue
line.physicsBody?.contactTestBitMask = CollisionTypes.atom.rawValue
self.addChild(line)
let wait = SKAction .wait(forDuration: 1.5)
let fade:SKAction = SKAction.fadeOut(withDuration: 1)
fade.timingMode = .easeIn
let remove: SKAction = SKAction.removeFromParent()
line.run(SKAction.sequence([wait, fade, remove]))
}
联络代表:
let contactA:SKPhysicsBody = contact.bodyA
let contactB:SKPhysicsBody = contact.bodyB
let nodeA = contactA.node
let nodeB = contactB.node
if contactA.categoryBitMask == 2 || contactB.categoryBitMask == 2 {
print("line hit")
}