从 SKNode 地板移除重力 Class

Remove Gravity From SKNode Floor Class

我在游戏开始时出现了两个矩形,但一旦开始,重力就会将它们拉下来。我在单独的 "Floor.swift" class 中获得了下面的代码。我还有一个包含以下信息的 "BitMaskCategories.swift" 文件。

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 

这是我的 "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")
    }
}

为什么我会收到错误消息,"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" 但是当我使用“?”时代替 ”!”该应用程序可以运行,但矩形会掉落。我需要那条线,以免他们那样做,我什至不明白这是怎么回事。

您正在尝试分配:.isDynamic = false 在对象初始化之前,

你应该移动leftWall.physicsBody!.isDynamic = false

之后 leftWall.physicsBody = SKPhysicsBody(rectangleOf: leftWall.size)

同样适用于:rightWall.physicsBody!.isDynamic = false,移动它

之后:rightWall.physicsBody = SKPhysicsBody(rectangleOf: rightWall.size)

所以您的代码可能是:

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)