Change SpriteNode PhysicsBody Size at Run Time
Asked Answered
U

1

7

I want to be able to change a node's physicsBody height when the user swipes downwards, but have not been able to find out how to do this, beside resetting the entire physicsBody.

When I originally load the node, I use the below code:

    nodeHero.color = UIColor .grayColor()
    nodeHero.size.width = 20
    nodeHero.size.height = 45
    nodeHero.position.x = -frame.size.width/2 + 45
    nodeHero.position.y = pointMainY + 30 + nodeHero.size.height/2
    nodeHero.zPosition = 110

    nodeHero.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(nodeHero.size.width, nodeHero.size.height))
    nodeHero.physicsBody?.mass = 1
    nodeHero.physicsBody?.angularVelocity = 0
    nodeHero.physicsBody?.allowsRotation = false
    nodeHero.physicsBody?.restitution = 0
    nodeHero.physicsBody?.categoryBitMask = bitHero

    addChild(nodeHero)

And when I swipe down, I want to be able to do something like this (this doesn't work):

    nodeHero.size.height = 28
    nodeHero.physicsBody?.size.height = 28

But instead I have to use the nodeHero.physicsBody = SKPhysicsBody() again, which resets all the other physicsBody properties, so I have to do this:

    nodeHero.size.height = 28

    nodeHero.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(nodeHero.size.width, nodeHero.size.height))
    nodeHero.physicsBody?.mass = 1
    nodeHero.physicsBody?.angularVelocity = 0
    nodeHero.physicsBody?.allowsRotation = false
    nodeHero.physicsBody?.restitution = 0
    nodeHero.physicsBody?.categoryBitMask = bitHero
Unpin answered 9/7, 2015 at 16:43 Comment(1)
If you run a scale action on a node it seems that its physics body will also change: #24638586Ferrocene
P
5

According to SpriteKit documentation the area of a SKPhysicsBody can't be modified, so you need to create another SKPhysicsBody instance and copy the values you want to keep from the previous instance.

Pronuba answered 1/12, 2015 at 7:53 Comment(1)
Ricardo Amores is right you can't resize physicsBody at run time you need to recreate it and assign back to your textureExcrement

© 2022 - 2024 — McMap. All rights reserved.