Line Following Mouse
Hi
Actually I already have a class that does this exact thing ![]()
you can enjoy it here - http://megaswf.com/serve/1154775
if you play around with it you will notice that the frame rate drops significantly when you move the mouse fast for a long time,
especially if you add more objects and logic to the game (press space and see what happens
)
my question is how can I make this efficiant and not affect the frame rate.
heres the code:
package { import adobe.utils.ProductManager; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.MovieClip; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; /** * ... * @7111211 Gadi G */ public class MouseHandler extends Sprite { private var _stage:DisplayObjectContainer; public var _bDraw:Boolean = false; private var _arrLine:Array = new Array();; private var _angle; private var _p1:Point = new Point(); private var _p2:Point = new Point(); private var cos:Number; private var sin:Number; private var lineDrawing:Line; private var angle; private var distance:uint; private static var instance:MouseHandler; public var _mousePos:Point = new Point(); public function MouseHandler() { } public static function getInstance():MouseHandler { if (instance == null) { instance = new MouseHandler(); } return instance; } public function startListening(prnt:DisplayObjectContainer) { _stage = prnt; _stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); _stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); } private function mouseDownHandler(e:MouseEvent):void { _bDraw = true; _p2.x = mouseX; _p2.y = mouseY; _stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler); _stage.addEventListener(MouseEvent.MOUSE_MOVE, drawMouseLine); } private function mouseUpHandler(e:MouseEvent):void { _bDraw = false; _stage.removeEventListener(MouseEvent.MOUSE_MOVE, drawMouseLine); } private function enterFrameHandler(e:Event):void { for each (var s:Line in _arrLine) { s.scaleX = s.scaleY *= .79; // the lowest possile value is one twip which is 0.05 if (s.width < .7) { _arrLine.splice(_arrLine.indexOf(s), 1); _stage.removeChild(s); s = null; } } if (!_bDraw) { //_mousePos = null; if (_arrLine.length == 0) { _stage.removeEventListener(Event.ENTER_FRAME, enterFrameHandler); } } _mousePos.x = mouseX; _mousePos.y = mouseY; } private function drawMouseLine(e:MouseEvent):void { _p1.x = mouseX; _p1.y = mouseY; _angle = Math.atan2(_p1.y - _p2.y,_p1.x - _p2.x); var rot:Number = (180 / Math.PI ) * _angle + 180; cos = Math.cos(_angle); sin = Math.sin(_angle); distance = Math.round(Point.distance(_p1,_p2)) + 1; while (--distance) { lineDrawing = new Line(); lineDrawing.x = _p2.x; lineDrawing.y = _p2.y; lineDrawing.rotation = rot; _arrLine.push(_stage.addChild(lineDrawing)); lineDrawing = null; _p2.x += cos; _p2.y += sin; } _p2.x = _p1.x; _p2.y = _p1.y; } } }
Thanks