如何使用SpriteKit绘制正弦线?

时间:2015-05-06 04:12:46

标签: objective-c sprite-kit osx-yosemite

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

1 个答案:

答案 0 :(得分:3)

基本步骤... 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;
}