draw a line in sprite kit in touchesmoved

后端 未结 1 532
Happy的楠姐
Happy的楠姐 2020-12-29 14:00

I would like to draw a line in sprite kit along the points collected in touchesmoved.

Whats the most efficient way of doing this? I\'ve tried a few times and my line

1条回答
  •  别那么骄傲
    2020-12-29 14:42

    You could define a CGpath and modify it by adding lines or arcs in your touch moved function. After that, you can create a SKShapeNode from your path and configure it as you prefer. If you want to draw the line while the finger is moving on the screen you can create the shape node when the touch begins with an empty path and then modify it.

    Edit: I wrote some code, it works for me, draws a simple red line.

    In your MyScene.m:

    @interface MyScene()
    {
        CGMutablePathRef pathToDraw;
        SKShapeNode *lineNode;
    }
    @end
    
    @implementation
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch* touch = [touches anyObject];
        CGPoint positionInScene = [touch locationInNode:self];
    
        pathToDraw = CGPathCreateMutable();
        CGPathMoveToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
    
        lineNode = [SKShapeNode node];
        lineNode.path = pathToDraw;
        lineNode.strokeColor = [SKColor redColor];
        [self addChild:lineNode];
    }
    
    - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
    {
        UITouch* touch = [touches anyObject];
        CGPoint positionInScene = [touch locationInNode:self];
        CGPathAddLineToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
        lineNode.path = pathToDraw;
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
    // delete the following line if you want the line to remain on screen.
        [lineNode removeFromParent];
        CGPathRelease(pathToDraw);
    }
    @end
    

    0 讨论(0)
提交回复
热议问题