不能在我的班级之外找到一个对象

时间:2016-01-04 21:56:40

标签: swift sprite-kit

我正在尝试将游戏开发为一个完整的初学者。我设置了一个游戏场景,它确实引用了一个名为taxiNode和BlockNode的对象。

我现在想要使事物具有交互性,并希望在点击BlockNode时在taxiNode上添加一个冲动。为此,我在我的BlockNode类中设置了func interact(),但是我无法访问我的TaxiNode。

这是我的BlockNode类的代码

    import SpriteKit

class BlockNode: SKSpriteNode, CustomNodeEvents, InteractiveNode {

    func didMoveToScene() {
        print("block added")
        userInteractionEnabled = true

    }

    func interact() {
        taxiNode.physicsBody!.applyForce(CGVectorMake(0, 400))

    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesEnded(touches, withEvent: event)
        print("destroy block")
        //interact()


    }

}

我的GameScene Class看起来像这样

    import SpriteKit

struct PhysicsCategory {
    static let None:  UInt32 = 0
    static let Taxi:  UInt32 = 0b1 // 1
    static let Block: UInt32 = 0b10 // 2
    static let Edge:   UInt32 = 0b100 // 4
    /* static let Edge:  UInt32 = 0b1000 // 8
    static let Label: UInt32 = 0b10000 // 16
    static let Spring:UInt32 = 0b100000 // 32
    static let Hook:  UInt32 = 0b1000000 // 64 */
}

protocol CustomNodeEvents {
    func didMoveToScene()
}

protocol InteractiveNode {
    func interact()
}


    class GameScene: SKScene, SKPhysicsContactDelegate {

    var taxiNode: TaxiNode!

    override func didMoveToView(view: SKView) {
        /* Setup your scene here */

        // Calculate playable margin
        let maxAspectRatio: CGFloat = 16.0/9.0 // iPhone 5
        let maxAspectRatioHeight = size.width / maxAspectRatio
        let playableMargin: CGFloat = (size.height - maxAspectRatioHeight)/2

        let playableRect = CGRect(x: 0, y: playableMargin,
            width: size.width, height: size.height-playableMargin*2)

        physicsBody = SKPhysicsBody(edgeLoopFromRect: playableRect)
        physicsWorld.contactDelegate = self
        physicsBody!.categoryBitMask = PhysicsCategory.Edge

        enumerateChildNodesWithName("//*", usingBlock: {node, _ in
            if let customNode = node as? CustomNodeEvents {
                customNode.didMoveToScene()
            }
        })

        taxiNode = childNodeWithName("taxi") as! TaxiNode

    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    }

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

我的BlockNode类

中出现以下错误

“使用未解析的标识符”taxiNode“

有没有人知道我需要修理哪些来解决出租车节点并让我接受我的冲动?

1 个答案:

答案 0 :(得分:1)

查找变量范围以了解更多信息。

你的阻止节点不知道什么是出租车节点,也不知道。

你需要做的是让你的blockNode知道出租车是什么。

要做到这一点,你必须传递它:

首先正确建立功能:

func interact(taxiNode : TaxiNode) {
    taxiNode.physicsBody!.applyForce(CGVectorMake(0, 400))

}

然后当你需要互动时:

blockNode.interact(taxiNode)

确保修复协议以解决此问题。

protocol InteractiveNode {
    func interact(taxiNode:TaxiNode)
}