Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

draw a line in sprite kit in touchesmoved

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 is either wrong on the y axis, or takes up a lot of processing power that the fps goes down to 10 a second.

Any ideas?

like image 907
dev6546 Avatar asked Nov 13 '13 12:11

dev6546


1 Answers

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
like image 175
membersheep Avatar answered Nov 17 '22 11:11

membersheep