获取任意位置与圆的切点的坐标

刚刚发的那个 获取任意位置与圆直径形成的等腰三角形的底边与圆的交点的坐标 其实没有多大用处,而这个用处就大了,可以在游戏中进行碰撞检测,在碰到圆形障碍物的时候求出最短的运行路径。

原理图

任意位置与圆切点坐标原理图

运行效果

请使用下面的链接升级 Flash Player 到最新版本:

安装最新的Flash Player插件

源码

SimpleSample6.as

 1/**
 2 * 计算鼠标位置与圆的切点坐标
 3 * */
 4package
 5{
 6    import flash.display.Sprite;
 7    import flash.events.MouseEvent;
 8    
 9    [SWF(width=400,height=400)]
10    public class SimpleSample6 extends Sprite
11    {
12        private var _centerX:Number;
13        private var _centerY:Number;
14        private var _radius:Number = 80;
15        
16        public function SimpleSample6()
17        {
18            _centerX = stage.stageWidth/2;
19            _centerY = stage.stageHeight/2;
20            draw();
21            drawTriangle(0, 0);
22            stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
23        }
24        
25        private function draw():void
26        {
27            graphics.clear();
28            graphics.lineStyle(1);
29            graphics.moveTo(0, stage.stageHeight/2);
30            graphics.lineTo(stage.stageWidth, _centerY);
31            graphics.moveTo(_centerX, 0);
32            graphics.lineTo(_centerX, stage.stageHeight);
33            graphics.drawCircle(_centerX, _centerY, _radius);
34        }
35        
36        private function drawTriangle($mouseX:Number, $mouseY:Number):void
37        {
38            var __dx:Number = _centerX - $mouseX;
39            var __dy:Number = _centerY - $mouseY;
40            //计算点击处与圆心相对于X轴的夹角
41            var __r1:Number = Math.atan2(__dy, __dx);
42            //计算点击处与圆心、点击处与切点1这两条线段间的夹角
43            var __d1:Number = Math.sqrt(__dx*__dx + __dy*__dy);
44            var __r2:Number = Math.asin(_radius/__d1);
45            //计算从切点1向圆的垂直直径做垂线形成的直角三角形的一个角
46            var __r3:Number = __r1 - __r2;
47            //计算坐标系中的角度
48            var __r4:Number = __r3 - Math.PI/2;
49            //计算切点1相对于圆心的x、y坐标
50            var __x1:Number = _radius * Math.cos(__r4);
51            var __y1:Number = _radius * Math.sin(__r4);
52            
53            //计算点击处与切线2相对于X轴的夹角
54            var __r5:Number = Math.PI/2 - __r1 - __r2;
55            //计算坐标系中的角度
56            var __r6:Number = -__r5;
57            //计算切点2相对于圆心的x、y坐标
58            var __x2:Number = _radius * Math.cos(__r6);
59            var __y2:Number = _radius * Math.sin(__r6);
60            
61            graphics.moveTo(_centerX, _centerY);
62            graphics.lineTo($mouseX, $mouseY);
63            graphics.lineTo(_centerX+__x1, _centerY+__y1);
64            graphics.lineTo(_centerX, _centerY);
65            graphics.lineTo(_centerX-__x2, _centerY-__y2);
66            graphics.lineTo($mouseX, $mouseY);
67        }
68        
69        private function mouseMoveHandler(evt:MouseEvent):void
70        {
71            draw();
72            drawTriangle(mouseX, mouseY);
73        }
74    }
75}