NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: challenge 1 for project 11. I can't load the images into an array

Forums > 100 Days of Swift

This is a game from project 11 where users drop ball from top of the scene, and they bounce off of blocks at the bottom. Currently, my game uses one ball that's colored red, and we have 6 other balls, all colored differently. I am trying to assign random ball everytime the game is launched. I have the 7 images in the assets folder. My initial thought was to load the images into an array, and then either shuffle that array, or select a random element from that array in the line where we assign the image. However, I have ran into a problem where my images aren't even loading into the array. Here's the code. I printed the count of the array that is supposed to hold the image, and it says 0 each time. Please take a look at my code and tell me what I am doing wrong? Look at the top of didMove() method to see where I try to load the images in to said array.

if my approach isn't right, also do let me know.

Thanks.

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate{
    var picsArray = [String]()
    var scoreLabel: SKLabelNode!
    var editLabel: SKLabelNode!
    var editingMode = false{
        didSet{
            if editingMode{
                editLabel.text = "Done"
            }
            else{
                editLabel.text = "Edit"
            }
        }
    }
    var score = 0 {
        didSet{
            scoreLabel.text = " score: \(score)"
        }
    }

    override func didMove(to view: SKView) {
        let fm = FileManager.default
        let path = Bundle.main.resourcePath!
        let items = try! fm.contentsOfDirectory(atPath: path)
        for item in items {
            if item.hasPrefix("ball"){
                picsArray.append(item)
            }
            print(picsArray.count)

        }

        physicsWorld.contactDelegate = self
        let background = SKSpriteNode(imageNamed: "background")
        background.position = CGPoint(x: 512, y: 384)
        background.blendMode = .replace
        background.zPosition = -1

        addChild(background)

        scoreLabel = SKLabelNode(fontNamed: "chalkduster")
        scoreLabel.text = "Score: 0"
        scoreLabel.horizontalAlignmentMode = .right
        scoreLabel.position = CGPoint(x: 980, y: 700)
        addChild(scoreLabel)

        editLabel = SKLabelNode(fontNamed: "chalkduster")
        editLabel.text = "Edit"
        editLabel.position = CGPoint(x: 80, y: 700)
        addChild(editLabel)

        physicsBody = SKPhysicsBody(edgeLoopFrom: frame)

        makeSlots(at: CGPoint(x: 128, y: 0), isGood: true)
        makeSlots(at: CGPoint(x: 384, y: 0), isGood: false)
        makeSlots(at: CGPoint(x: 640, y: 0), isGood: true)
        makeSlots(at: CGPoint(x: 896, y: 0), isGood: false)

        makeBouncer(at: CGPoint(x: 0, y: 0))
        makeBouncer(at: CGPoint(x: 256, y: 0))
        makeBouncer(at: CGPoint(x: 512, y: 0))
        makeBouncer(at: CGPoint(x: 768, y: 0))
        makeBouncer(at: CGPoint(x: 1024, y: 0))

        // Get label node from scene and store it for use later

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else{return}
        let location = touch.location(in: self)

        let objects = nodes(at: location)

        if objects.contains(editLabel){
            editingMode.toggle()
        }
        else{

            if editingMode{
                let size = CGSize(width: Int.random(in: 16...128), height: 16)
                let box = SKSpriteNode(color: UIColor(red: CGFloat.random(in: 0...1), green: CGFloat.random(in: 0...1), blue: CGFloat.random(in: 0...1), alpha: 1), size: size)
                box.zRotation = CGFloat.random(in: 0...3)
                box.position = location
                box.physicsBody = SKPhysicsBody(rectangleOf: box.size)
                box.physicsBody?.isDynamic = false
                addChild(box)
            }

            else{

                let ball = SKSpriteNode(imageNamed: "ballRed")
                ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2.0)
                ball.physicsBody?.restitution = 0.4
                ball.physicsBody?.contactTestBitMask = ball.physicsBody?.collisionBitMask ?? 0
                ball.position = location
                ball.name = "ball"
                addChild(ball)
            }
        }
    }

            func makeBouncer(at position: CGPoint){
                let bouncer = SKSpriteNode(imageNamed: "bouncer")
                bouncer.position = position
                bouncer.physicsBody = SKPhysicsBody(circleOfRadius: bouncer.size.width/2)
                bouncer.physicsBody?.isDynamic = false
                addChild(bouncer)
            }

            func makeSlots(at position: CGPoint, isGood: Bool){
                var slotBase: SKSpriteNode
                var slotGlow: SKSpriteNode

                if isGood{
                    slotBase = SKSpriteNode(imageNamed: "slotBaseGood")
                    slotGlow = SKSpriteNode(imageNamed: "slotGlowGood")
                    slotBase.name = "good"
                } else{
                    slotBase = SKSpriteNode(imageNamed: "slotBaseBad")
                    slotGlow = SKSpriteNode(imageNamed: "slotGlowBad")
                    slotBase.name = "bad"
                }
                slotGlow.position = position

                slotBase.position = position
                slotBase.physicsBody = SKPhysicsBody(rectangleOf: slotBase.size)
                slotBase.physicsBody?.isDynamic = false
                addChild(slotGlow)
                addChild(slotBase)

                let spin = SKAction.rotate(byAngle: .pi, duration: 1)
                let spinforever = SKAction.repeatForever(spin)
                slotGlow.run(spinforever)
            }

            func collision(between ball: SKNode, object: SKNode){
                if object.name == "good"{
                    destroy(ball: ball)
                    score+=1
                }
                else{
                    if object.name == "bad"{
                        destroy(ball: ball)
                        score-=1
                    }
                }
            }

            func destroy(ball: SKNode){
                ball.removeFromParent()
            }

            func didBegin(_ contact: SKPhysicsContact) {

                guard let nodeA = contact.bodyA.node else{return}
                guard let nodeB = contact.bodyB.node else{return}

                if nodeA.name == "ball"{
                    collision(between: nodeA, object: nodeB)
                }
                else if nodeB.name == "ball"{
                    collision(between: nodeB, object: nodeA)
                }
            }

        }

   

You are trying to read the files from your Bundle, but you have them in your Assets instead. That is why your array is empty. There are no files in your App bundle that have the prefix "ball" because they are in your Assets.

In my project, I just manually created the array with the names of each file for the different colored balls. But, I'm not sure if there is a better way to do it that can read them directly from the Assets.

1      

@fly0strich, thanks for the clarification, that's a disticntion I did not know! anyways, I didn't wanna drag the folder into the projects like we did in project 1, and I though creating the array manually was less efficient but it does get the job done. If there's a better way to do it, I am sure someone will let us know.

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.