That looks pretty good. The straight line problems come in because of your use of ratio, which is not altogether a bad approach, but obviously goes to 0 or NaN in those cases. You could just put in special case logic for those two cases to come up with a random small ratio (for the 0 case) and a random large ratio (for the NaN case).
The iterative approach you've taken here is a pretty good compromise between complexity and end effect. For comparison, here's pseudocode to do the recursive approach I outlined before.
This code is completely untested and therefore probably has fatal flaws.Code:private function drawLightning( p1:Vector2D, p2:Vector2D, color:uint ) : void { g.lineStyle( 1, color ); drawLightningRecursive(p1, p2, 3); } private function drawLightningRecursive(p1:Vector2D, p2:Vector2D, depth:int):void{ if (depth == 0){ //draw rather than recurse here g.moveTo(p1.x, p1.y); g.lineTo(p2.x, p2.y); return; } //calculate midpoint var midp:Vector2D = new Vector2D((p1.x+p2.x)/2, (p1.y+p2.y)/2); //offset midpoint by a bit. var dist:Number = Math.sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y-p2.y)*(p1.y-p2.y)); var offsetDist:Number = dist/5; //arbitrary divisor. midp.x += (Math.random()*offsetDist)-offsetDist; midp.y += (Math.random()*offsetDist)-offsetDist; drawLightningRecursive(p1, midp, depth-1); drawLightningRecursive(midp, p2, depth-1); }




Reply With Quote