I found this post while trying to draw a line on each mouseDown, of the example xCode / OS X / Game (aka SpriteKit)/ Application.
You can copy/paste this code into GameScene.swift. It should draw a line on each mouse-down event by user. Looks 'etch-a-sketch'-style.
import SpriteKit
var lastPoint: CGPoint = CGPoint(x: 0.0, y: 0.0)
var newPoint: CGPoint = CGPoint(x: 100.0, y: 100.0)
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.backgroundColor = SKColor.blackColor()
let myLabel = SKLabelNode(fontNamed:"default")
myLabel.text = "SKSpriteNode Draw Lines";
myLabel.fontSize = 15;
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
override func mouseDown(theEvent: NSEvent) {
/* Called when a mouse click occurs */
let location = theEvent.locationInNode(self)
newPoint = location
let pathToDraw:CGMutablePathRef = CGPathCreateMutable()
let myLine:SKShapeNode = SKShapeNode(path:pathToDraw)
CGPathMoveToPoint(pathToDraw, nil, lastPoint.x, lastPoint.y)
CGPathAddLineToPoint(pathToDraw, nil, newPoint.x, newPoint.y)
lastPoint = newPoint
myLine.path = pathToDraw
myLine.strokeColor = SKColor.whiteColor()
self.addChild(myLine)
}
}
For the newbies, this is what my xCode project looks like:
For the small handful iOS of folks. Same code as above ported to touchBegan of the example iOS / Game (aka SpriteKit) / Application default project.
Put this code in your GameScene.swift file
import SpriteKit
var lastPoint: CGPoint = CGPoint(x: 0.0, y: 0.0)
var newPoint: CGPoint = CGPoint(x: 100.0, y: 100.0)
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.backgroundColor = SKColor.blackColor()
let myLabel = SKLabelNode(fontNamed:"default")
myLabel.text = "SKSpriteNode Draw Lines";
myLabel.fontSize = 15;
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
newPoint = location
let pathToDraw:CGMutablePathRef = CGPathCreateMutable()
let myLine:SKShapeNode = SKShapeNode(path:pathToDraw)
CGPathMoveToPoint(pathToDraw, nil, lastPoint.x, lastPoint.y)
CGPathAddLineToPoint(pathToDraw, nil, newPoint.x, newPoint.y)
lastPoint = newPoint
myLine.path = pathToDraw
myLine.strokeColor = SKColor.whiteColor()
self.addChild(myLine)
}}}
Enjoy.