0
votes

So I'm building a Sprite Kit game and at a certain point I want to enable/disable gravity on some of my nodes.

I managed to do it but I just was wondering if there is a better way to achieve this.

Here's my code:

func enableGravity() {
    for rawBubble in container!.children {
        let bubble = rawBubble as SKShapeNode
        bubble.physicsBody?.dynamic = true
    }
}

When not using type inference on rawBubble, I get this error : SKPhysicsBody? does not have a member named dynamic

I guess this is not really a Sprite Kit related issue but more Swift itself. Is it possible to do this in a more simple way?

Thanks.

1
There is an affectedByGravity property which would probably be better for you in this case. The dynamic property controls if physics affects your objects. Also, at least one node has to be dynamic for a contact or collision event to take place. Therefor, changing the dynamic property back and forth will most likely lead you to monitor more things than you have to. - meisenman
I really wanted the bubbles to not be affected by anything so dynamic was relevant but thanks I forgot this property. - Skoua

1 Answers

1
votes

Since container!.children is an [AnyObject], you're going to have to cast its contents before you can do anything all that useful with them. The cleanest way I can think of is just to cast it to a [SKNode] right in your for statement:

func enableGravity() {
    for bubble in container!.children as [SKNode] {
        bubble.physicsBody?.dynamic = true
    }
}