Search code examples
iosobjective-cswiftsprite-kituitouch

Create a straight line with SpriteKit


How can I create a straight line using SpriteKit and UITouch?

I wanted a method that allowed me to add the start point and the end point instead of a path. Just like a rubber band.


Solution

    1. Create a SKShapeNode that is a line when user begins the touch movement e.g. in touchesBegan:.

      SKShapeNode *line = [SKShapeNode node];
      CGPoint startPoint = CGPointMake(..., ...)
      CGPoint endPoint = CGPointMake(..., ...)
      
      CGMutablePathRef pathToDraw = CGPathCreateMutable();
      CGPathMoveToPoint(pathToDraw, NULL, startPoint.x, startPoint.y);
      CGPathAddLineToPoint(pathToDraw, NULL, endPoint.x, endPoint.y);
      
      line.path = pathToDraw;
      line.strokeColor = [UIColor redColor]];
      [self addChild:line];
      
    2. Modify its path to change its length in touchesMoved: