Glutch
Glutch

Reputation: 720

Updating SKPhysicsBody rectangleOfSize

So i have a paddle/bar, when that bar collides with a ball, it shrinks. I also want to update to SKPhysicsBody of the paddle/bar so that it keeps the same collisionbox as the visual sprite. How do I accomplish this?

Here is my current code, located inside an didBeginContact-collision function

bar.size = CGSizeMake(16 * playerLife, 16)
bar.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 16 * playerLife, height: 64))

The bar.size works as intended. physicsBody rectangleOfSize makes the game crash.

Update: included more code in response to comment

bar.size = CGSizeMake(16 * playerLife, 16)
bar.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 16 * playerLife, height: 64))


func CollisionWithDeathBar(ball: SKSpriteNode, deathBar: SKSpriteNode) {
    playerLife--
    bar.size = CGSizeMake(16 * playerLife, 16)
    shouldResizePaddle = true
}

override func didSimulatePhysics() {
    if shouldResizePaddle {
        bar.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 16 * playerLife, height: 64))
        shouldResizePaddle = false
    }
}

Upvotes: 1

Views: 260

Answers (1)

rickster
rickster

Reputation: 126107

Modifying physics bodies during a physics contact callback is not allowed.

(Think about it. During an update to the physics simulation, SpriteKit has to examine all the physics bodies in the world, find collisions, and call contact handlers for each of them. If you could change the bodies in the midst of all that, you'd have undefined, or at least ill-defined, results.)

I'd recommend using the contact function to schedule a change of physics body to happen later. Something like this:

var shouldResizePaddle = false

func didBeginContact(_ contact: SKPhysicsContact) {
    if /* paddle/ball contact */ {
        shouldResizePaddle = true
    }
}

override func didSimulatePhysics() {
    if shouldResizePaddle {
        bar.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 16 * playerLife, height: 64))
        shouldResizePaddle = false
    }
}

Upvotes: 4

Related Questions