如何有效地在SpriteKit中绘制一条线

时间:2016-08-19 13:02:04

标签: ios objective-c ios7 sprite-kit line-drawing

在我的SpriteKit场景中,用户应该能够用他/她的手指画线。我有一个有效的解决方案,如果线很长,FPS下降到4-6并且线开始变为多边形,如下图所示:

enter image description here

要绘制mylineSKShapeNode*),我会以这种方式收集NSMutableArray* noteLinePoints中的触摸点移动

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint touchPoint = [[touches anyObject] locationInNode:self.scene];
    SKNode *node = [self nodeAtPoint:touchPoint];

    if(noteWritingActive)
    {
        [noteLinePoints removeAllObjects];
        touchPoint = [[touches anyObject] locationInNode:_background];
        [noteLinePoints addObject:[NSValue valueWithCGPoint:touchPoint]];
        myline = (SKShapeNode*)node;
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(myline)
    {
        CGPoint touchPoint = [[touches anyObject] locationInNode:_background];
        [noteLinePoints addObject:[NSValue valueWithCGPoint:touchPoint]];
        [self drawCurrentNoteLine];
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(myline)
    {
        myline.name = @"note";
        myline = nil;
    }
    NSLog(@"touch ended");
}

我以这种方式画线

- (CGPathRef)createPathOfCurrentNoteLine
{
    CGMutablePathRef ref = CGPathCreateMutable();

    for(int i = 0; i < [noteLinePoints count]; ++i)
    {
        CGPoint p = [noteLinePoints[i] CGPointValue];
        if(i == 0)
        {
            CGPathMoveToPoint(ref, NULL, p.x, p.y);
        }
        else
        {
            CGPathAddLineToPoint(ref, NULL, p.x, p.y);
        }
    }

    return ref;
}

- (void)drawCurrentNoteLine
{
    if(myline)
    {
        SKNode* oldLine = [self childNodeWithName:@"line"];
        if(oldLine)
            [self removeChildrenInArray:[NSArray arrayWithObject:oldLine]];

        myline = nil;

        myline = [SKShapeNode node];
        myline.name = @"line";
        [myline setStrokeColor:[SKColor grayColor]];

        CGPathRef path = [self createPathOfCurrentNoteLine];
        myline.path = path;
        CGPathRelease(path);

        [_background addChild:myline];
    }
}

如何解决此问题?因为所有后续行都只是多边形,我认为因为fps非常低而且触摸的采样率自动也很低......

请注意,对于测试,我使用的是iPad 3(我的应用程序需要使用iOS7的iPad 2模型)

1 个答案:

答案 0 :(得分:3)

不要经常创建新的SKShapeNodes,有一个错误导致你的减速。相反,只使用1 SKShapeNode(或创建一堆但重用它们),并使用新信息附加路径(因此不需要不断地将myline添加到背景中)

替代:

使用1个社区SKSkapeNode来渲染路径,然后将SKShapeNode转换为带有view.textureFromNode的纹理,然后使用此新纹理添加SKSpriteNode而不是形状节点