How to draw a line in Sprite-kit

Waruna picture Waruna · Sep 30, 2013 · Viewed 29.7k times · Source

How can one draw a line in Sprite-kit? For example if I want to draw a line in cocos2d, I could easily using ccDrawLine();

Is there an equivalent in sprite-kit?

Answer

Rajneesh071 picture Rajneesh071 · Sep 30, 2013

Using SKShapeNode you can draw line or any shape.

SKShapeNode *yourline = [SKShapeNode node];
CGMutablePathRef pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, 100.0, 100.0);
CGPathAddLineToPoint(pathToDraw, NULL, 50.0, 50.0);
yourline.path = pathToDraw;
[yourline setStrokeColor:[SKColor redColor]];
[self addChild:yourline];

Equivalent for Swift 4:

var yourline = SKShapeNode()
var pathToDraw = CGMutablePath()
pathToDraw.move(to: CGPoint(x: 100.0, y: 100.0))
pathToDraw.addLine(to: CGPoint(x: 50.0, y: 50.0))
yourline.path = pathToDraw
yourline.strokeColor = SKColor.red
addChild(yourline)