SpriteKit applyImpulse崩溃

时间:2015-06-19 23:15:00

标签: swift sprite-kit

当我尝试在我的节点应用崩溃时使用applyImpulse并收到此消息:fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) 这是代码:

    self.character.physicsBody = SKPhysicsBody(rectangleOfSize: character.size)
    self.character.physicsBody?.affectedByGravity = true
    self.character.physicsBody?.categoryBitMask = PhysicsCategory.PlayerCat
    self.character.physicsBody?.contactTestBitMask = PhysicsCategory.ObstaclesCat
    self.character.physicsBody?.dynamic = true
    self.character.physicsBody?.mass = 5
    self.character.physicsBody?.friction = 0.5
    self.character.physicsBody?.restitution = 0

我的applyImpulse:     character.physicsBody?.applyImpulse(CGVectorMake(0,100)) 我尝试了一些事情,现在问题是SKPhysicsBody的大小是零,但为什么呢?即使我尝试手动设置大小,也是如此。

3 个答案:

答案 0 :(得分:0)

这意味着您正在尝试将一个动作或物理应用到一个空的非存在节点上,因此它会崩溃。

答案 1 :(得分:0)

import SpriteKit

class GameScene: SKScene {
    let character = SKSpriteNode(imageNamed: "Rectangle.png")

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        self.physicsWorld.gravity = CGVectorMake(0, -1.0)

        self.character.position = CGPointMake(self.size.width * 0.5, self.size.height * 0.5)

        self.addChild(self.character)
        self.character.physicsBody = SKPhysicsBody(rectangleOfSize: character.size)
        self.character.physicsBody?.affectedByGravity = true
//        self.character.physicsBody?.categoryBitMask = PhysicsCategory.PlayerCat
//        self.character.physicsBody?.contactTestBitMask = PhysicsCategory.ObstaclesCat
        self.character.physicsBody?.dynamic = true
        self.character.physicsBody?.mass = 5
        self.character.physicsBody?.friction = 0.5
        self.character.physicsBody?.restitution = 0
    }

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        /* Called when a touch begins */
        self.character.physicsBody?.applyImpulse(CGVectorMake(0, 1000))

    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

答案 2 :(得分:0)

改变角色&#39;到&#39; var character&#39;。而且无需添加“自我”。在排队之前。