思路:
1、首先将圆的中心点,都转换为以矩形的边为X/Y的坐标系;
2、做AABB矩形和圆的相交检测;
代码如下:
/** * 将一个点,按照指定的坐标信息(原点,旋转),转换为另外一个点 * @param p 原始点 * @param base 新的坐标原点 * @param angle 新左边系X轴的旋转角度 * @return 新点的数据 * */ public static function convertLocalPoint(p:Point, base:Point, angle:Number):Point { var matrix :Matrix = new Matrix(); //matrix.createBox(1, 1, -angle*Math.PI/180, -base.x, -base.y); matrix.translate(-base.x, -base.y); matrix.rotate(-angle*Math.PI/180); var p2 :Point = matrix.transformPoint(p); return p2; } /** * 判定一个圆形,是否和矩形相交(矩形的边和XY坐标轴对齐) * @param center * @param radius * @param min * @param max * @return * */ public static function intersectCircleAABB(center:Point, radius:Number, min:Point, max:Point) : Point { var closestPoint:Point = center.clone(); if( center.x < min.x ) closestPoint.x = min.x; else if( center.x > max.x ) closestPoint.x = max.x; if( center.y < min.y ) closestPoint.y = min.y; else if( center.y > max.y ) closestPoint.y = max.y; var diff:Point = closestPoint.subtract( center ); if( diff.x * diff.x + diff.y * diff.y > radius * radius ) return null; return closestPoint; } /** * 判定一个圆和一个矩形是否碰撞 * @param center * @param radius * @param loc * @param angle * @param width * @param height * @return true/碰撞 false/不碰撞 * */ public static function checkRectCircleCollide(center:Point, radius:Number, loc:Point, angle:Number, width:Number, height:Number):Boolean { var min :Point = new Point(0, -height/2); var max :Point = new Point(width, height/2); trace('center:', center, 'radius:', radius, 'loc:', loc, 'angle:', angle, 'width:', width, 'height:', height); var center2 :Point = convertLocalPoint(center, loc, angle); var result :Point = intersectCircleAABB(center2, radius, min, max); trace('center2:', center2, 'min:', min, 'max:', max); return result!=null; }
测试代码:
[Test] public function testMatrix():void { var base :Point = new Point(0,0); var angle :Number = 7.454; var p :Point = new Point(137, 14); var p1 :Point = Vector2Extension.convertLocalPoint(p, base, angle); trace("p", p, "p1", p1); base = new Point(2266,2049); angle = 7.454; p = new Point(2403, 2063); p1 = Vector2Extension.convertLocalPoint(p, base, angle); trace("p", p, "p1", p1); var p2 :Point = Vector2Extension.intersectCircleAABB(new Point(500,500), 142, new Point(10,10), new Point(900,900)); trace(p2); }