This question is almost self-explanatory: I need to use SpriteKit to draw a line that looks like a sine wave, but I will also need to vary the amplitude of this wave later.
Asked
Active
Viewed 617 times
0
-
Google "iOS draw sine wave". – sangony May 06 '15 at 12:45
-
@sangony that leads me to this question: http://stackoverflow.com/questions/23985840/drawing-an-infinite-sine-wave That wasn't what I wanted. Instead, I wanted to draw a sine wave **with variable amplitude.** This question has been answered already. – DDPWNAGE May 07 '15 at 01:52
1 Answers
3
The basic steps...1) Create an SKShapeNode
, 2) Generate a sinusoid CGPath, and 3) Assign the CGPath to the shape node's path
attribute
-(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;
}

0x141E
- 12,613
- 2
- 41
- 54