I am starting to work with Cocos2D and so far learned a lot. But I can't find how to simulate a ccDrawLine so that it behavior like a guitar string, meaning, when touching a ccDrawLine, that it plays sound and moves the ccDrawLine where the user is touching it.
2 Answers
I've no experience with Cocos2D, but the process to simulate a guitar string may be something like so:
- Draw your line;
- Add a valid "touch area" around the string (as the small string may not be thick enough to reliably register a touch);
- When you detect a touch within the bounds of the touch area, animate the line to simulate the strum, and play the sound (and fade it out, to simulate the slowing of the vibration).
Another thing to consider may be the possibility of overlapping sound. What if the user rapidly touches the same string? The previous sound should stop before the new sound starts. Or, more naturally, no sound should play whilst the user still has their finger on the string, and should instead only produce a sound once the user has "plucked" the string (ie. ended the touch).
I'm not sure if Cocos2D has its own touch event handler (I imagine it would), but perhaps this SO post might help: how can i detect the touch event of an UIImageView
EDIT: It turns out, Cocos2D does have its own touch event handler. See: How can I detect touch in cocos2d?
I would go about this by using a free and simple vector art tool such as Inkscape. It will allow you to make some realistic-looking strings of different thicknesses/textures. Import the strings into your app as different sprites. Cocos2d has a lot of options for easily detecting things like 'isTouchOnNode', which perfectly fits your scenario. Specifically, http://kobold2d.com does wonders for easy touch detection and node selection.
I don't have access to Xcode at the moment, so this may not be verbatim code:
/* if you use Kobold2d */
CCSprite* Gstring = [CCSprite spriteWithFile:@"Gstring.png"];
KKInput* input = [KKInput sharedInput];
if ([input isAnyTouchOnNode:Gstring touchPhase:KKTouchPhaseAny])
{
// play a sound.
// this code will become extremely complicated
// if you want a realistic sound
}
Keep in mind that cocos2d may not be the best engine to use if you are planning on making a sound/music heavy app. It has a very basic 'SimpleAudioEngine' from CocosDenshion that is not designed to handle the many overlapping sounds a guitar can make.

- 1,568
- 1
- 15
- 28