1

每当我运行我的项目时,我都会收到一个错误的指令错误...

ground.physicsBody!.dynamic = false

这是我运行此代码段的完整代码。我不确定发生了什么,而且我对可选选项没有很多经验。

代码:

var ground = SKSpriteNode()
ground.position = CGPointMake(0, 0)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, 30))
let groundTexture = SKTexture(imageNamed: "Red.png")
ground = SKSpriteNode(texture: groundTexture)
ground.physicsBody!.dynamic = false
ground.physicsBody?.allowsRotation = false

ground.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
ground.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
ground.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
self.addChild(ground)
4

1 回答 1

5

您在创建其物理体后重新初始化 ground,因此新对象没有物理体,因此显示零错误。

将您的代码更改为

let groundTexture = SKTexture(imageNamed: "Red.png")
var ground = SKSpriteNode(texture: groundTexture)
ground.position = CGPointMake(0, 0)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, 30))
ground.physicsBody!.dynamic = false
ground.physicsBody?.allowsRotation = false

ground.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
ground.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
ground.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
self.addChild(ground)

根据评论,当您在展开选项时遇到 found nil错误时,一般做法是使用 any?或 aif let来安全地展开。在这种情况下,它可以像这样实现

if let physicsBodyObject = ground.physicsBody {
    physicsBodyObject.dynamic = false
    physicsBodyObject.allowsRotation = false
    //other code
}
于 2016-06-03T16:02:43.980 回答