如何使用touchesMoved函数正确更新曲线?

时间:2015-07-26 11:51:10

标签: swift sprite-kit

我想制作一条曲线,当用户移动他们的手指时,曲线改变了它的弧度,但我所做的代码似乎有些不对劲,当我移动手指时有很多曲线:( 这是我下面的代码,并遵循可怕的构建截图。实际上我也想知道如何用UIPanGestureRecognizer实现这个功能。

import SpriteKit
import AVFoundation
import UIKit

class Home: SKScene {

    var happiness:CGFloat {
        return currentPoint.y
    }

    var currentPoint = CGPoint(x: 0, y: 1024)

    override func didMoveToView(view: SKView) {
        backgroundColor = UIColor.blueColor()
    }

    func drawhappiness() {
        let pathNew2 = CGPathCreateMutable()
        let startx:CGFloat = 268
        let starty:CGFloat = 1024
        let cp1x:CGFloat = 568
        let cp1y:CGFloat = happiness
        let cp2x:CGFloat = 968
        let cp2y:CGFloat = happiness
        let endx:CGFloat = 1292
        let endy:CGFloat = 1024
        CGPathMoveToPoint(pathNew2, nil, startx, starty)
        CGPathAddCurveToPoint(pathNew2, nil, cp1x, cp1y, cp2x, cp2y, endx, endy)
        let shapeNew2 = SKShapeNode()
        shapeNew2.path = pathNew2
        shapeNew2.strokeColor = UIColor.greenColor()
        shapeNew2.lineWidth = 10
        addChild(shapeNew2)
    }

    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
        for touch:AnyObject in touches {
            currentPoint = touch.locationInNode(self)
        }
    }

    override func update(currentTime: NSTimeInterval) {
        drawhappiness()
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

每次移动手指时,都会向场景添加新的形状节点。要解决此问题,请在Home中创建具有全局范围的单个形状,在didMoveToView中配置形状(即设置线宽,颜色),并在{{更新形状的path属性中1}}。

例如,

drawhappiness