2015-05-06 76 views
0

這個問題幾乎不言自明:我需要使用SpriteKit繪製一條看起來像正弦波的線,但我還需要稍後改變此波的振幅。如何使用SpriteKit繪製正弦曲線?

+0

谷歌 「的iOS畫正弦波」。 – sangony

+0

@sangony,導致我到這個問題:http://stackoverflow.com/questions/23985840/drawing-an-infinite-sine-wave 這不是我想要的。相反,我想繪製一個幅度可變的正弦波**。這個問題已經得到了回答。 – DDPWNAGE

回答

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; 
} 
+0

老兄......你搖滾。謝謝! – DDPWNAGE