Skip to main content
Donovan’s Vision Blog

Reset physics in entities

When building a Jenga game, I wanted to be able to reset the pieces. I was able to write a simple reset method that put the pieces back to where they should be but there was an unexpected result. Each time I press Reset, the pieces fall over:

Jenga game without physics reset code

Object physics #

The video above shows that the pieces are being reset into their positions, but they still have their movement physics in place. As a result when reset, they continue to move causing the tower to collapse.

Reset the physics #

We can apply to lines of code to reset the physics. First we set the piece to static, then call clearForcesAndTorques.

modelEntity.physicsBody?.mode = .static
modelEntity.clearForcesAndTorques()

We then need to run a loop over the pieces to re-enable the physics:

for child in tower.children {
    if let modelEntity = child as? ModelEntity {
        modelEntity.physicsBody?.mode = .dynamic
    }
}

As a result we should now be able to set the pieces and they should stay still:

Jenga game with physics reset code