现在的位置: 首页 > 综合 > 正文

求两直线的交点

2013年03月01日 ⁄ 综合 ⁄ 共 1070字 ⁄ 字号 评论关闭
  1. /**
  2.     * 求直线AB, CD的交点
  3.     * 如果平行, 返回null.
  4.     * 
  5.     * @param a : Point 
  6.     * @param b : Point 
  7.     * @param c : Point 
  8.     * @param d : Point 
  9.     * @return Point - 交点
  10.     * @usage <code>
  11.     * import com.seyself.math.GeomMath;
  12.     * var a = { x:0 , y:0 };
  13.     * var b = { x:200 , y:200 };
  14.     * var c = { x:100 , y:0 };
  15.     * var d = { x:50 , y:200 };
  16.     * trace( GeomMath.intersection( a, b, c, d ) ); // 输出 : (x=80, y=80)
  17.     * </code>
  18.     */
  19.     public static function intersection( a:Object, b:Object, c:Object, d:Object ):Point
  20.     {
  21.         var pos1 = (b.y-a.y)/(b.x-a.x);
  22.         var pos2 = (d.y-c.y)/(d.x-c.x);
  23.         var pi = Number.POSITIVE_INFINITY;
  24.         var ni = Number.NEGATIVE_INFINITY;
  25.         
  26.         if(pos1==pos2){
  27.             return null;
  28.         }
  29.         if( pos1 == ni || pos1 == pi ){
  30.             pos1 = b.y-a.y;
  31.         }
  32.         if( pos2 == ni || pos2 == pi ){
  33.             pos2 = d.y-c.y;
  34.         }
  35.         
  36.         var nx = ( ( a.x*pos1 ) - a.y - ( c.x*pos2 ) + c.y )/( pos1-pos2 );
  37.         var ny = pos1*( nx-a.x ) + a.y;
  38.         
  39.         return new Point( nx, ny );
  40.     }

抱歉!评论已关闭.