Search code examples
swiftsprite-kitskphysicsbodygameplay-kit

How to reset the alignment of physics bodies in SpriteKit?


I´ve made a game with SpriteKit with different bricks falling down on a hill. When these physical bodies fall down they usually bounce off the hill and change their alignment(they spin a couple of times). If I transition to the GameOver scene and press replay(back to the GameScene) the physics bodies are still aligned like when I left the scene. But I want them to have a horizontal alignment like in the beginning.

GameScene:

import SpriteKit
import GameplayKit

 let hillTexture = SKTexture(imageNamed: "HillIllustration")
 let hillIllustration = SKSpriteNode(texture: hillTexture)

 let brickTexture = SKTexture(imageNamed: "BrickIllustration")
 let brick = SKSpriteNode(texture: brickTexture)

 class GameScene: SKScene {

    //Hill

    hillIllustration.setScale(0.7)
    hillIllustration.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.16)
    hillIllustration.zPosition = 2
    hillIllustration.physicsBody = SKPhysicsBody(polygonFrom: clipPath)
    hillIllustration.physicsBody?.isDynamic = false
    hillIllustration.physicsBody?.categoryBitMask = CollisionBitMask.Hill
    hillIllustration.physicsBody?.affectedByGravity = false
    self.addChild(hillIllustration)

    //The brick is a child of the hill node

    brick.setScale(1)
    brick.position = CGPoint(x: -350, y: self.size.height * 0.5)
    brick.zPosition = 1
    brick.physicsBody = SKPhysicsBody(polygonFrom: clipPath2)
    brick.physicsBody?.isDynamic = true
    brick.physicsBody?.categoryBitMask = CollisionBitMask.Brick
    brick.physicsBody?.affectedByGravity = true
    hillIllustration.addChild(brick)

}

Transition to GameOver:

let transition = SKTransition.crossFade(withDuration: 0)
let gameScene = GameOver(size: self.size)
self.view?.presentScene(gameScene, transition: transition)

Transition back to GameScene:

let transition = SKTransition.crossFade(withDuration: 0)
    let gameScene = GameScene(size: self.size)
    self.view?.presentScene(gameScene, transition: transition)

Somehow when I transition scenes the information of how the bricks were aligned gets saved. How can I change that?


Solution

  • if you want that after you restart the game the brick node go back to start rotation than call:

    brick.zRotation = 0
    

    if you want that during the game the node do not rotate than you may put this code in the update func that already have in all spritekit files:

    override func update(_ currentTime: TimeInterval) {
     brick.zRotation = 0
    }
    

    Hope this helps