【问题标题】:SKSpriteNode physics body created from texture results in nil value从纹理创建的 SKSpriteNode 物理体的值为零
【发布时间】:2020-02-07 08:48:45
【问题描述】:

我目前正在开发一款小型 iOS 游戏。在当前的迭代中,20 个目标会在屏幕空间入侵者风格中生成并移动,您可以控制一艘小船射击并摧毁它们。我在此期间编写的目标代码、玩家飞船的子弹和一个简单的碰撞检测函数如下:

class Red_Target: SKSpriteNode{

    var game_scene: GameScene!
    private var ship_texture: SKTexture!

    convenience init(scale: CGFloat, game_world: GameScene){
        self.init(texture: SKTexture(imageNamed: "Proto Target"))
        self.ship_texture = SKTexture(imageNamed: "Proto Target")
        self.setScale(scale)
        game_scene = game_world
        game_scene.addChild(self)
        self.position = CGPoint(x: game_scene.view!.bounds.width/10, y: 9 * game_scene.view!.bounds.height/10)
        //self.physicsBody = SKPhysicsBody(texture: ship_texture, size: self.size)
        self.physicsBody = SKPhysicsBody(circleOfRadius: 13)
        self.physicsBody!.affectedByGravity = false
        self.physicsBody!.collisionBitMask = 0x0
        self.physicsBody!.categoryBitMask = CollisionType.Enemy.rawValue
        self.physicsBody!.contactTestBitMask = CollisionType.Player_Bullet.rawValue
    }

    func move() {
        self.run(space_invaders(scene: game_scene))
    }

}

class PC_Bullet: SKSpriteNode{

    convenience init(scale: CGFloat){
        self.init(imageNamed: "Goodbullet")
        self.setScale(scale)
        self.physicsBody = SKPhysicsBody(circleOfRadius: 3)
        self.physicsBody!.affectedByGravity = false
        self.physicsBody!.categoryBitMask = CollisionType.Player_Bullet.rawValue
        self.physicsBody!.collisionBitMask = 0x0
        self.physicsBody!.contactTestBitMask = CollisionType.Enemy.rawValue
    }


}

    func didBegin(_ contact: SKPhysicsContact) {
        contact.bodyA.node!.removeFromParent()
        contact.bodyB.node!.removeFromParent()
    }

}

这段代码在当前迭代中运行良好。但是,如果将目标的物理体定义为其纹理的行未注释并且将物理体定义为 circleOfRadius 的行被删除,则游戏将在第 5 个目标被摧毁后持续崩溃,并声称 didBegin 解包为 nil 值。为什么这只发生在带有纹理的物理物体上?有什么办法可以更改代码以使其正常工作吗?我希望以后在处理更多不规则形状时能够使用纹理函数中的物理体。

【问题讨论】:

标签: swift sprite-kit


【解决方案1】:

你犯了一个经典的nooby错误。你过早地移除你的身体。如果您浏览 Stackoverflow,您会发现很多解决方法。

基本思想是在物理阶段结束之前不要移除您的精灵,因为您的 1 个精灵可能有多个接触点需要处理。所以想出一种方法来标记需要删除的精灵,并在 didSimulatePhysics 函数期间将其删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多