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

标签 ios swift collision contacts

我在尝试将 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 接触时,我收到消息“无法将 bodyA 转换到 Spring ”。 spring 类看起来像这样:

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 类,因为 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


}

关于ios - 为什么我不能将 ContactBody 转换为 SpriteKit 中的自定义 SKNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172000/

相关文章:

processing - buggy 弹跳球

c++ - 2D障碍物碰撞

iphone - 中断 iPhone IOS 5 上的通话/短信

ios - 横向模式下的 Swift Collection View

ios - 使用启动屏幕 (.xib) 停止缩放

ios - 如何避免在 SpriteKit 中传递 currentTime ?

ios - Swift 4.1 JWT http header 承载在服务器中返回401

java - 寻找碰撞面?

ios - VC 用 UISlider 更改 VC2 上的文本字段

objective-c - 使用Core Graphics在Objective-C(IOS)中绘制角度/角度/"Conical"/"Arcing"渐变