0

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!

Joy Lucas
  • 61
  • 1
  • 10

1 Answers1

1

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
}
bg2b
  • 1,939
  • 2
  • 11
  • 18
  • For `node` I get the error: "Static member 'node' cannot be used on instance of type 'GameScene' Insert SKNode". So I changed it to `contact.bodyB.node` but know the if statement doesn't get called at all. – Joy Lucas May 03 '20 at 10:46
  • `node` was just an example. The shape node in the collision may be from either `bodyA` or `bodyB`. You have to examine the category bitmasks or names or whatever to identify which node is the correct one. If the node you attempt to reference `as?` a shape node isn't of that type, the cast will not succeed and the `if` won't be executed. – bg2b May 03 '20 at 13:09