Search code examples
iosobjective-csprite-kitskshapenode

Drawing line with SpriteKit and detecting collision


I have managed to draw a line with array of my random CGPoints.

    -(void)drawLine
    {
    SKShapeNode *mainLine = [SKShapeNode node];
    CGMutablePathRef pathToDraw = CGPathCreateMutable();
    CGPathMoveToPoint(pathToDraw, NULL, 0, 0);

    for(int i;i<pointsInMyView.count;i++)
    {
        CGPoint myPoint = [pointsInMyView[i] CGPointValue];
        CGPathAddLineToPoint(pathToDraw, NULL, myPoint.x, myPoint.y);
        mainLine.path = pathToDraw;
    }
    [mainLine setLineWidth:40];
    [mainLine setStrokeColor:[SKColor whiteColor]];
    mainLine.name = @"mainLine";
    [self addChild:mainLine];


}

As you can see I am drawing a SKShapeNode. My goal is to check collision of my SKSpriteNode with my line. But of course, this shape node makes a frame that contains all points of my line, and in this case my ShapeNode is all over my view. My SpriteNode detects collision with this ShapeNode all the time. I should draw multiple different ShapeNodes I guess, so every node would have its own frame. But if i do it this way, my line is not connected. Is there some solution to draw this node by node and still get nice line.


Solution

  • Unfortunately nodes in SpriteKit cannot be concave (http://mathworld.wolfram.com/ConcavePolygon.html), with lines that cross over each other.

    You will have to create separate nodes for each lines between adjacent points and then possibly join them together. you could do this either by:

    1. Create the 1st segment and then add subsequent segments as children of that 1st segment.
    2. Create a non-visible node for the whole line and add wll the line segments as children of that node.
    3. Create physicsbodies for each segment and join them with SKPhysicsJointFixed.