先来看一下效果:
实现代码:
/** * 勾股树 * @param g Graphics
* @param p1 起始点1
* @param p2 起始点2 * @param angle 每次迭代时的偏移角(弧度) * @param n 迭代次数 */ function gouguTree(g:Graphics, p1:Point, p2:Point, angle:Number, n:int):void { /* * p5 * /\ * p3/A \p4 * +---+ * | | * +---+ * p1 p2 */ var p3:Point, p4:Point, p5:Point; var length:Number; var p1_p2:Point = p2.subtract(p1); var baseAngle:Number = Math.atan2(p1_p2.y, p1_p2.x); length = p1_p2.length; p3 = p1.add( Point.polar(length, baseAngle + Math.PI/2) ); p4 = p3.add(p1_p2); g.moveTo(p1.x, p1.y); g.lineTo(p2.x, p2.y); g.lineTo(p4.x, p4.y); g.lineTo(p3.x, p3.y); g.lineTo(p1.x, p1.y); if(n > 0) { //if(length > 10) { //改为此句将会当长度小于10时结束。 /* * cosA = |p3_p5| / |p3_p4| * |p3_p5| = cosA * |p1_p2| (p3_p4 = p1_p2) */ var p3_p4:Point = p4.subtract(p3); var l_p3_p5:Number = Math.cos(angle) * length; p5 = p3.add( Point.polar(l_p3_p5, baseAngle + angle) ); trace("@l_p3_p5",l_p3_p5); n--; gouguTree(g, p3, p5, angle, n); gouguTree(g, p5, p4, angle, n); } }
没有评论:
发表评论