Search code examples
iosswiftsprite-kitdrawuibezierpath

Swift 3/SpriteKit - Draw independent shapes with finger


I'm a beginner following the tutorial here for drawing shapes in Swift.

import SpriteKit

class GameScene: SKScene {

    var activeSlice: SKShapeNode!
    var activeSlicePoints = [CGPoint]()

    override func didMove(to view: SKView) {
        createSlices()
    }

    func createSlices() {
        activeSlice = SKShapeNode()
        activeSlice.strokeColor = UIColor(red: 1, green: 0.9, blue: 0, alpha: 1)
        activeSlice.lineWidth = 9
        addChild(activeSlice)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if let touch = touches.first {
            let location = touch.location(in: self)
            activeSlicePoints.append(location)
            redrawActiveSlice()
        }
    }

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

    }

     override func touchesEnded(_ touches: Set<UITouch>?, with event: UIEvent?) {
}

    func redrawActiveSlice() {
        let path = UIBezierPath()
        path.move(to: activeSlicePoints[0])
        for i in 1 ..< activeSlicePoints.count {
            path.addLine(to: activeSlicePoints[i])
        }
        activeSlice.path = path.cgPath
    }
}

With this code, when you release the finger then touch again to draw, you have a line connecting the two shapes. I would like to draw independent shapes. Perhaps by modifying the code so that for each instance of touchesEnded(), the array of points that represents the shape is stored in a multidimensional array, and by creating an array of points for each new instance of touchesBegan()?

Thank you for your help.


Solution

  • It's something like

    override func touchesEnded(_ touches: Set<UITouch>?, with event: UIEvent?) {
    
         createSlices()
    }