Swift 3 / SpriteKit - 用手指绘制独立的形状

时间:2017-05-09 16:42:14

标签: ios swift sprite-kit draw uibezierpath

我是教程here之后的初学者,用于在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
    }
}

使用此代码,当您松开手指然后再次触摸绘制时,您有一条线连接两个形状。 我想绘制独立的形状。 也许通过修改代码使得对于touchesEnded()的每个实例,表示形状的点数组存储在多维数组中,并为touchesBegan()的每个新实例创建一个点数组?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

就像

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

     createSlices()
}