swiftxcodesprite-kitskshapenodeskphysicscontact

How to change the fillColor of a SKShapeNode within the didBegin contact function?


My goal is to change the fillColor of a SKShapeNode as soon as that node collides with another Node. I do know how to edit the physics body at the point of collision but I couldn't manage to figure out how to change properties like fill- or strokeColor of a Node.

The SKShapeNode:

    func addBrick() -> SKShapeNode {

    let brick = SKShapeNode(rect: CGRect(x: -100, y: -20, width: 200, height: 40), cornerRadius: 20)
    brick.fillColor = .blue
    brick.strokeColor = .blue
    brick.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 200, height: 40))
    brick.position = CGPoint(x: 0, y: -50)
    brick.zPosition = 2

    brick.physicsBody?.categoryBitMask = BrickCategory
    brick.physicsBody?.collisionBitMask = PlayerCategory
    brick.physicsBody?.contactTestBitMask = PlayerCategory

    return brick
}

Then I test the contact between the player and the brick:

    func didBegin(_ contact: SKPhysicsContact) {
    let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch contactMask {
    case PlayerCategory | BrickCategory:
        print("")



    default:
        print("Unknown collision")
    }
}

I do know that I can make changes to the physics body itself by using

contact.bodyB.node?.//make changes here

, but I don't know how to change the fillColor of bodyB for example to red.

I appreciate your help!


Solution

  • If you have an SKNode node that you know should be an SKShapeNode, then you can cast it like:

    if let shapeNode = node as? SKShapeNode {
        shapeNode.fillColor = .red
    }