I am currently trying to implement in SpriteKit that previously generated SpriteNodes bounce off a line drawn by the user. For this I need to give them a physicsbody so that the objects can collide. Does anyone have an idea how to implement this? Thanks a lot!
Here is the code block:
-- Update: Problem is solved! Working code in this question. --
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]))
}
ContactDelegate:
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")
}
There are different types of physics body (circular, rectanglular, polygonal, alpha mask, edge based). For CGMutablePath, you want to create a chain from a path. To implement it, replace this line:
line.physicsBody? = SKPhysicsBody()
With this:
line.physicsBody = SKPhysicsBody(edgeChainFrom: path)