从SKNode Floor Class中删除重力

时间:2017-12-22 00:34:00

标签: swift sprite-kit skspritenode skphysicsbody

我有两个在游戏开始时出现的矩形,但一旦开始,重力就会将它们拉下来。我在下面的单独的“Floor.swift”类中得到了代码。我还有一个“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”课程

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")
    }
}

为什么我会收到错误,“线程1:致命错误:在解开可选值时意外发现nil”但是当我使用“?”时代替 ”!”该应用程序工作,但矩形下降。我需要那条线,以便他们不要这样做,我甚至不知道这有多大意义。

1 个答案:

答案 0 :(得分:3)

您正尝试分配:.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)