cut circle
/**
* Copyright lizhi ( http://wonderfl.net/user/lizhi )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/kbjN
*/
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
/**
* ...
* //http://game-develop.net/
* //http://www.thecodeway.com/blog/?p=1873
* @author lizhi
*/
public class Cut extends Sprite
{
private var r:Number;
private var cx:Number;
private var cy:Number;
private var x0:Number=0;
private var y0:Number=0;
private var x1:Number=0;
private var y1:Number=0;
private var tf:TextField;
public function Cut()
{
r = 100;
cx = 465/2;
cy = 465/3;
stage.addEventListener(MouseEvent.MOUSE_DOWN, stage_mouseDown);
draw();
tf = new TextField;
addChild(tf);
tf.text = "draw line";
tf.autoSize="left";
}
private function stage_mouseDown(e:MouseEvent):void
{
x0 = mouseX;
y0 = mouseY;
stage.addEventListener(MouseEvent.MOUSE_UP, stage_mouseUp);
stage.addEventListener(MouseEvent.MOUSE_MOVE, stage_mouseMove);
}
private function stage_mouseMove(e:MouseEvent):void
{
draw();
x1 = mouseX;
y1 = mouseY;
graphics.moveTo(x0, y0);
graphics.lineTo(x1, y1);
var A:Number = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
var B:Number = 2 * ((x1 - x0) * (x0 - cx) + (y1 - y0) * (y0 - cy));
var C:Number = cx * cx + cy * cy + x0 * x0 + y0 * y0 - 2 * (cx * x0 + cy * y0) - r * r;
var bb_plus_4ac:Number = B * B - 4 * A * C;
if (bb_plus_4ac > 0)
{
var sqrt:Number = Math.sqrt(bb_plus_4ac);
var u1:Number = (-B + sqrt) / 2 / A;
var u2:Number = (-B - sqrt) / 2 / A;
var cutx1:Number = x0 + (x1 - x0) * u1;
var cuty1:Number = y0 + (y1 - y0) * u1;
var cutx2:Number = x0 + (x1 - x0) * u2;
var cuty2:Number = y0 + (y1 - y0) * u2;
if(u1<0||u1>1)graphics.lineStyle(0, 0xff00);
else graphics.lineStyle(0, 0xff0000);
graphics.drawCircle(cutx1, cuty1, 2);
if(u2<0||u2>1)graphics.lineStyle(0, 0xff00);
else graphics.lineStyle(0, 0xff0000);
graphics.drawCircle(cutx2, cuty2, 2);
}
tf.text="bb_plus_4ac:"+bb_plus_4ac+" u1:"+u1+" u2:"+u2;
}
private function stage_mouseUp(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, stage_mouseUp);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, stage_mouseMove);
}
private function draw():void {
graphics.clear();
graphics.lineStyle(0);
graphics.drawCircle(cx, cy, r);
}
}
}