如何使用 SpriteKit 绘制正弦线?

How to draw a sine line using SpriteKit?

这个问题几乎是不言自明的:我需要使用 SpriteKit 绘制一条看起来像正弦波的线,但稍后我还需要改变这个波的幅度。

基本步骤...1) 创建一个 SKShapeNode,2) 生成一个正弦曲线 CGPath,以及 3) 将 CGPath 分配给形状节点的 path 属性

-(void)didMoveToView:(SKView *)view {        
    self.scaleMode = SKSceneScaleModeResizeFill;

    // Create an SKShapeNode
    SKShapeNode *node = [SKShapeNode node];
    node.position = CGPointMake(300.0, 300.0);
    // Assign to the path attribute
    node.path = [self sineWithAmplitude:20.0 frequency:1.0 width:200.0
                               centered:YES andNumPoints:32];

    [self addChild:node];
}

// Generate a sinusoid CGPath
- (CGMutablePathRef)sineWithAmplitude:(CGFloat)amp frequency:(CGFloat)freq
                                width:(CGFloat)width centered:(BOOL)centered
                         andNumPoints:(NSInteger)numPoints {

    CGFloat offsetX = 0;
    CGFloat offsetY = amp;

    // Center the sinusoid within the shape node
    if (centered) {
        offsetX = -width/2.0;
        offsetY = 0;
    }

    CGMutablePathRef path = CGPathCreateMutable();

    // Move to the starting point
    CGPathMoveToPoint(path, nil, offsetX, offsetY);
    CGFloat xIncr = width / (numPoints-1);

    // Construct the sinusoid
    for (int i=1;i<numPoints;i++) {
        CGFloat y = amp * sin(2*M_PI*freq*i/(numPoints-1));
        CGPathAddLineToPoint(path, nil, i*xIncr+offsetX, y+offsetY);
    }

    return path;
}