【问题标题】:How to draw a line in SpriteKit efficiently如何在 SpriteKit 中有效地画一条线
【发布时间】:2016-12-26 15:46:39
【问题描述】:

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

为了绘制myline (SKShapeNode*),我以这种方式在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 进行测试(我的应用需要在 iPad 2 型号和 iOS7 上运行)

【问题讨论】:

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


    【解决方案1】:

    不要不断地创建新的SKShapeNodes,有一个错误会导致你的速度变慢。相反,只使用 1 SKShapeNode (或者创建一堆但重复使用它们),并在路径中附加新信息(因此无需不断将 myline 添加到后台)

    替代方案:

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

    【讨论】:

    • 我的用户应该能够画出他/她想要的尽可能多的线条,无论如何我会尝试始终重用相同的 SKShapeNode。感谢您的快速回答!
    • NP,也许他们会在 iOS 10 中修复 SKShapeNodes
    • @ddb 我发布了一个可能更适合您的替代答案
    • 好吧,我忘了在我的问题中提到我的应用程序需要在带有 iOS7 的 iPad2 型号上运行......我不是很幸运......
    • 这是一个商业应用,他们不会这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    相关资源
    最近更新 更多