Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change SpriteNode PhysicsBody Size at Run Time

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
like image 749
Jarron Avatar asked Jul 09 '15 16:07

Jarron


1 Answers

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.

like image 135
Ricardo Amores Avatar answered Sep 29 '22 15:09

Ricardo Amores