在Sprite Kit中的touchesmoved方法中画一条线。

8
我希望在Sprite Kit中绘制沿着touchesmoved收集的点的线条。
最有效的方法是什么?我尝试了几次,我的线条要么在y轴上错误,要么占用了很多处理能力,使fps降至每秒10帧。
有什么想法吗?
1个回答

17
你可以在触摸移动函数中定义一个CGpath并通过添加线条或弧线来修改它。之后,你可以从路径创建SKShapeNode,并根据需要进行配置。 如果希望在手指在屏幕上移动时绘制线条,可以在触摸开始时使用空路径创建形状节点,然后进行修改。
编辑:我编写了一些代码,对我很有效,可以画出简单的红线。
在你的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

出于好奇,如果您绘制10秒钟,帧速率表现如何?它会开始下降吗? - prototypical
在我的实现中,帧率保持不变。 - membersheep
为什么我什么都看不到?节点计数增加,但在绘图时没有任何可见的东西,我甚至注释掉了最后几行以保留该行。 - 4GetFullOf
你是在你的类中实现了这段代码还是尝试作为独立的代码运行? - membersheep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接