passing info from collectionView to gameScene

前端 未结 2 1153
盖世英雄少女心
盖世英雄少女心 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 18:58

    Couple of ways to do this. One of them is using NSUserDefaults.

    To store data in NSUserDefaults, do this:

    // object can be almost anything. Strings, arrays, dictionaries...
    
    NSString *object = @"WellDone";
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:object forKey:@"Hamburger"];
    [defaults synchronize];
    

    To read NSUserDefaults, do this:

    NSString *myString = [[NSUserDefaults standardUserDefaults] objectForKey:@"Hamburger"];
    

    The key being that you use the same key as when you created it.

    And of course, read the docs (blah,blah, blah).

    0 讨论(0)
  • 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. =)

    0 讨论(0)
提交回复
热议问题