passing info from collectionView to gameScene

前端 未结 2 1152
盖世英雄少女心
盖世英雄少女心 2021-01-25 18:35

I have created a game using SpriteKit (GameScene and GameViewController) and Objective-C. Everything there works fine. Within the same App I have created a UIViewController and

2条回答
  •  醉梦人生
    2021-01-25 19:10

    I approached this in a different way. Basically:

    1. Cell has the skview and loads and presents scene.
    2. Scene exposes properties (like a label for the months in the example)
    3. In the cellForItemAt of the collectionView datasource, I instantiate the scene and just use the exposed properties.

    Here is in code:

    Step 1:

    class GameCell: UICollectionViewCell {
    
        @IBOutlet weak var myskview: SKView!
    
        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
    
            if let scene = SKScene(fileNamed: "MyScene") as? MyScene{
                scene.scaleMode = .aspectFill
                myskview.presentScene(scene)
            }
        }
    }
    

    Step 2:

    class MyScene: SKScene {
        var gameLabel: SKLabelNode!
        var monthValue: String?
        var bird: SKSpriteNode?
        var floor: SKSpriteNode?
        var bgColor: UIColor?
        let birdCategory: UInt32 = 0x1 << 0
        let floorCategory: UInt32 = 0x1 << 1
    
        override func didMove(to view: SKView) { }
    

    Step 3:

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GameCell", for: indexPath) as! GameCell
    let scene = cell.myskview.scene as! MyScene
    scene.gameLabel.text = monthComponents[indexPath.row]
    

    Just don't forget to create the label inside the scene using:

    gameLabel = scene?.childNode(withName: "gameLabel") as! SKLabelNode
    

    You can check the final result in my git: https://github.com/tennydesign/spriteKitAndCollectionView

    Just pardon my dust. =)

提交回复
热议问题