Dewan
Dewan

Reputation: 519

Remove Gravity From SKNode Floor Class

I've got two rectangles that show up in the beginning of my game but once it starts, gravity takes them down. I've got the code below in a separate "Floor.swift" class. I also have a "BitMaskCategories.swift" file with the info below.

let ballCategory : UInt32 = 0x1 << 1
let avoidCategory : UInt32 = 0x1 << 2
let floorCategory : UInt32 = 0x1 << 3
let pointCategory : UInt32 = 0x1 << 4
let lifeCategory : UInt32 = 0x1 << 5 

And here is my "Floor.swift" class

import Foundation
import SpriteKit

class Floor: SKNode {
    override init() {
        super.init()

        let leftWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 50, height: 300))
        leftWall.position = CGPoint(x: 0, y: 100)
        leftWall.physicsBody!.isDynamic = false
        leftWall.physicsBody = SKPhysicsBody(rectangleOf: leftWall.size)
        self.addChild(leftWall)

        let rightWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 50, height: 300))
        rightWall.position = CGPoint(x: 100, y: 200)
       rightWall.physicsBody!.isDynamic = false
        rightWall.physicsBody = SKPhysicsBody(rectangleOf: rightWall.size)
        self.addChild(rightWall)

        // self.physicsBody?.affectedByGravity = false
        // self.physicsBody?.isDynamic = false

        // Set the bit mask properties
        self.physicsBody?.categoryBitMask = balloonCategory
        self.physicsBody?.contactTestBitMask = nailDropCategory | pointCategory | lifeCategory
        //self.physicsBody?.collisionBitMask = balloonCategory
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemted")
    }
}

Why do I get the error, "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" but when I use a "?" instead of "!" the app works but the rectangles fall. I need that line in order for them not to do that and I don't even get how this makes sense.

Upvotes: 1

Views: 162

Answers (1)

mugx
mugx

Reputation: 10105

You are trying to assign: .isDynamic = false before the object initialization,

you should move leftWall.physicsBody!.isDynamic = false

after leftWall.physicsBody = SKPhysicsBody(rectangleOf: leftWall.size)

and the same for: rightWall.physicsBody!.isDynamic = false, move it

after: rightWall.physicsBody = SKPhysicsBody(rectangleOf: rightWall.size)

so your code might be:

let leftWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 50, height: 300))
leftWall.position = CGPoint(x: 0, y: 100)
leftWall.physicsBody = SKPhysicsBody(rectangleOf: leftWall.size)
leftWall.physicsBody!.isDynamic = false
self.addChild(leftWall)

let rightWall = SKSpriteNode(color: UIColor.brown, size: CGSize(width: 50, height: 300))
rightWall.position = CGPoint(x: 100, y: 200)
rightWall.physicsBody = SKPhysicsBody(rectangleOf: rightWall.size)
rightWall.physicsBody!.isDynamic = false
self.addChild(rightWall)

Upvotes: 3

Related Questions