How do I update the curve correctly using the touchesMoved function?
I want to make a curve as if the user moved his finger, the curve changed his radian, but the code I did looked somehow wrong, with many curves when I moved my finger :( Here is my code below and followed horrible screenshot Actually I also want how to implement this functionality with 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()
}
}
source to share
You add a new shape node to the scene every time you move your finger. To fix this, create a single shape with a global area in Home
, set the shape in didMoveToView
(i.e. set line width, color) and update the shape property path
in drawhappiness
.
For example,
class Home: SKScene {
let shapeNew2 = SKShapeNode()
var currentPoint = CGPoint(x: 0, y: 1024)
var happiness:CGFloat {
return currentPoint.y
}
override func didMoveToView(view: SKView) {
backgroundColor = UIColor.blueColor()
shapeNew2.strokeColor = UIColor.greenColor()
shapeNew2.lineWidth = 10
addChild(shapeNew2)
}
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)
shapeNew2.path = pathNew2
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch:AnyObject in touches {
currentPoint = touch.locationInNode(self)
}
}
override func update(currentTime: NSTimeInterval) {
drawhappiness()
}
}
source to share