为什么我不能将 ContactBody 转换为 SpriteKit 中的自定义 SKNode

Why can't I cast ContactBody to a custom SKNode in SpriteKit

我在尝试将 ContactBody 转换为自定义 SKNode 时遇到问题。实现如下所示:

    case PhysicsCategory.player | PhysicsCategory.spring:
        if contact.bodyA.categoryBitMask == PhysicsCategory.spring{

            if let theSpring = contact.bodyA.node as? Spring
            {
                theSpring.printMsg()
            }else{
               print("can't cast bodyA to spring")
            }
        }else{
            if let theSpring = contact.bodyB.node as? Spring
            {
                theSpring.printMsg()
            }else{
                print("can't cast bodyB to spring")
            }
        }

当玩家与 spring 建立联系时,我收到消息 "can't cast bodyA to spring." spring class 看起来像这样:

import SpriteKit
class Spring: SKNode {

var impulse: Int
var sprite: SKSpriteNode
var textureAtlas: SKTextureAtlas
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
init (launchSpeed: Int){
    impulse = launchSpeed
    textureAtlas = SKTextureAtlas(named: "NonTiledItems")
    sprite = SKSpriteNode(texture: textureAtlas.textureNamed("spring01"))
    sprite.physicsBody =  SKPhysicsBody(rectangleOfSize: sprite.size)
    sprite.physicsBody!.categoryBitMask = PhysicsCategory.spring // could we make this button?
    sprite.physicsBody!.allowsRotation = false
    sprite.physicsBody!.dynamic = false
    sprite.physicsBody!.affectedByGravity = false
    sprite.physicsBody!.friction = 0.6
    sprite.physicsBody!.collisionBitMask = PhysicsCategory.player
    super.init()
    addChild(sprite)
}

func printMsg(){
    print("contact Made")
}
}

我不明白为什么 ContactBody 不会投射到 Spring class 因为 spring 继承自 SKNode。如果有人有任何建议,将不胜感激。

您的物理体连接到 SKSpriteNode,而不是 Spring。您需要删除 skspritenode 引用,您需要 Spring 成为 SKSpriteNode 的子节点,并且您需要像这样编写一个方便的 init:

convenience init (launchSpeed: Int)    
{
    self.SKSpriteNode(texture: SKTextureAtlas(named: "NonTiledItems").textureNamed("spring01"))
    impulse = launchSpeed

    self.physicsBody =  SKPhysicsBody(rectangleOfSize: self.size)
    self.physicsBody!.categoryBitMask = PhysicsCategory.spring // could we make this button?
    self.physicsBody!.allowsRotation = false
    self.physicsBody!.dynamic = false
    self.physicsBody!.affectedByGravity = false
    self.physicsBody!.friction = 0.6
    self.physicsBody!.collisionBitMask = PhysicsCategory.player


}