3

I have different 6 colored circles falling from the top of my screen. With each node, you are supposed to swipe in a different direction to score a point(red circle; swipe up, blue circle; swipe down, etc) but if the user swipes in a different direction than the one assigned to that particular node, it ends the game.

Im very unfamiliar with swipe gestures, so I have no code but help is very appreciated.

How I'm generating my nodes:

   func array() {
    let colorCount = 5
    let index=Int(arc4random_uniform(UInt32(colorCount)))
    let colors = SKSpriteNode(imageNamed: "Color\(index+1)")
    colors.size = CGSizeMake(130, 130)
    colors.position = CGPointMake(size.width / 2, 650)
    addChild(colors)
    colors.runAction(
        SKAction.moveByX(0, y: -1600,
            duration: NSTimeInterval(8.5)))
     }

They are removed from the scene by simply falling below the bottom of the scene.

KeepItSimple
  • 133
  • 8

1 Answers1

1

You can add gesture recognizer like this:

class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        /* Setup your scene here */

        let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedRight:"))
        swipeRight.direction = .Right
        view.addGestureRecognizer(swipeRight)
    }

    func swipedRight(sender:UISwipeGestureRecognizer){
        print("swiped right")
    }
}

Do the same for other directions. So, when you spawn a node, you can set a variable which stores current node's type (or color) and based on that, check if user has swiped in right direction.

Hint:

Keep in mind, that you can run into memory problems if you are adding a gesture recognizer each time the scene is loaded. This might happen because recognizers are added to the view instead of the scene, so no matter if scene is deallocated, recognizers will stay alive. Read more here.

EDIT:

This is a workable example which slightly differs from your current implementation, but in general, it does the same thing. You can just copy and paste to see how it works. It should give you an idea in which directions you can go to solve problems like :

  • how to track the color of the current node
  • how to create a subclass of SKSpriteNode
  • how to can remove the node when it end-up offscreen
  • probably some more (like how to update a label automatically when score is incremented)

    enum Color:UInt32 {
    
        case Red            // 0 - texture should be Color0@2x.png
        case Blue           // 1 - texture should be Color1@2x.png
        //case Green        // 2 - texture should be Color2@2x.png
        //case Yellow       // 3 - texture should be Color3@2x.png
        case NumberOfColors 
    }
    
    class Circle:SKSpriteNode {
    
        let textureColor:Color
    
        //Initialize a circle with color and size
        init(textureColor:Color, size:CGSize){
    
            self.textureColor = textureColor
            super.init(texture: SKTexture(imageNamed: "Color\(textureColor.rawValue)"), color:.clearColor(), size: size)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    }
    
    class GameScene: SKScene {
    
        let label = SKLabelNode(fontNamed: "ArialMT")
    
        var score: Int = 0 {
            didSet {
                label.text = "Score: \(score)"
            }
        }
    
        var currentCircle:Circle?
    
        func spawnRandomCircle() {
    
            //Randomize a circle. If you fail to randomize index correctly, default circle will be blue.
            let index = arc4random_uniform(Color.NumberOfColors.rawValue) 
            let circle = Circle(textureColor: Color(rawValue: index) ?? Color.Blue, size: CGSize(width: 50, height: 50))
            circle.position = CGPointMake(size.width / 2, 650)
            addChild(circle)
    
            //Move circle (and remove it, if end-up offscreen)
            let move = SKAction.moveByX(0, y: -1600, duration: NSTimeInterval(8.5))
            let moveAndRemove = SKAction.sequence([move, SKAction.removeFromParent()])
            circle.runAction(moveAndRemove, withKey:  "moving")
    
            //Update currentCircle
            currentCircle = circle
        }
    
        override func didMoveToView(view: SKView) {
    
            //Setup score label
            addChild(label)
            label.position = CGPoint(x: frame.minX+50, y: frame.maxY-50) //Put a score label in top left corner
            label.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Left
            label.text = String(score)
    
            //Create gesture recognizers
            let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedUp:"))
            swipeUp.direction = .Up
            view.addGestureRecognizer(swipeUp)
    
            let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedDown:"))
            swipeDown.direction = .Down
            view.addGestureRecognizer(swipeDown)
    
            //Spawn first circle
            spawnRandomCircle()
        }
    
        //This method accepts the Color associated with a certian swipe direction 
        //eg. if Swipe Up is detected, Red color will be passed ...
        func validateSwipe(color:Color){
    
            if let circle = currentCircle {
    
                circle.removeFromParent()
                if circle.textureColor == color {++score} else {--score}
                spawnRandomCircle()
            }
    
        }
    
        func swipedUp(sender:UISwipeGestureRecognizer){
             validateSwipe(Color.Red) //Red circle - Swipe Up
        }
        func swipedDown(sender:UISwipeGestureRecognizer){
             validateSwipe(Color.Blue) //Blue circle - Swipe Down
        }
    }
    

This can be done in many different ways and if you have questions feel free to ask...

Community
  • 1
  • 1
Whirlwind
  • 14,286
  • 11
  • 68
  • 157
  • Can you give me an example of the variable for the node? Im a little stuck. – KeepItSimple Feb 15 '16 at 01:46
  • @KeepItSimple Update your question to show how you create circles (do you use SKShapeNode, or SKSpriteNode, or subclass of one of these two) so I can make an appropriate answer... Also, you should mention how you move circles and at which point you remove them from the scene... – Whirlwind Feb 15 '16 at 01:53
  • Edited. I hope my last sentence makes sense to you. – KeepItSimple Feb 15 '16 at 01:57
  • @KeepItSimple Yeah, I understand what you meant...Currently, those nodes are just off-screen, but still in the node graph, so you should remove them. I will try to cover that in my edit as well... – Whirlwind Feb 15 '16 at 02:00