Drawing a spring in AS3 using recursion
by Ian
Recursion is when a function calls itself, iterating forever until escaped. This is awesome for consolidating code at the expense of readability. This drawSpring function recursively draws a spring using curveTo.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | graphics.clear(); graphics.lineStyle(1, 0); graphics.moveTo(-200, -200); drawSpring(-200, -200, 200, 200, 100); //x0 and y0 are the starting coordinates. //x1 and y1 are the end coordinates. //length specifies how long the spring is, and determines the amount of coils. //scale affects the diameter of the spring. //span affects the distance between <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/display/Graphics.html#curveTo()">curveTo</a> segments (smaller = more detail). //starting rotation and the beginning iteration can also be specified. function drawSpring(x0:int, y0:int, x1:int, y1:int, length:int = 1000, scale:Number = 20, span:Number = .5, rotation:Number = 0, iteration:int = 0, anchorX:int = -1, anchorY:int = -1, controlX:int = -1, controlY:int = -1 ):void { if(anchorX > -1){ graphics.curveTo(anchorX, anchorY, (controlX + anchorX) * .5, (controlY + anchorY) * .5); } iteration++; if (iteration < length) { drawSpring(x0, y0, x1, y1, length, scale, span, rotation - span, iteration, controlX, controlY, x0 + (x1 - x0) / length * iteration + scale * Math.cos(rotation - span), y0 + (y1 - y0) / length * iteration + scale * Math.sin(rotation - span)); }else graphics.curveTo(controlX, controlY, x1, y1); } |
Also, google ‘recursion’ for a smile. Be sure to spell it right!

Comments
[...] This post was mentioned on Twitter by Axna popular, seacloud9. seacloud9 said: Drawing a spring in #AS3 using recursion: http://bit.ly/ddylcm [...]