views:

261

answers:

1

Hi all, can anyone please help me on this. attached is the fla which has a part of code i am working on for a project.

with help of mouse you can draw a circle on the image, but for some reasons the mouse up event does not work. it works fine when the eventlisteners is attached to the stage, but does not work when its attached to the movieclip.

also how can i restrict the circle to be drawn only inside the movieclip which is a rectangle.

here is the code

    const CANVAS:Sprite = new Sprite();
var _dragging:Boolean = false;
var _corner:Point;
var _corner2:Point;

menFront.addEventListener(MouseEvent.MOUSE_DOWN, setAnchor);
menFront.addEventListener(MouseEvent.MOUSE_UP, completeRect);


function setAnchor(e:MouseEvent):void{
    trace("mouse down");
    if(!_dragging){
        CANVAS.graphics.clear(); 

        _corner = new Point(e.stageX, e.stageY);
        _dragging = true;
        menFront.addEventListener(MouseEvent.MOUSE_MOVE, liveDrag);
    }
}

function completeRect(e:MouseEvent):void{
    trace("mouse up");
    if(_dragging){    
        _dragging = false;
        menFront.removeEventListener(MouseEvent.MOUSE_MOVE, liveDrag);
        CANVAS.graphics.lineStyle(0, 0, 0);
        CANVAS.graphics.beginFill(0x222222,.5)

     _corner2 = new Point(e.stageX, e.stageY);
     trace(Point.distance(_corner,_corner2).toFixed(2));
     CANVAS.graphics.drawCircle(_corner.x, _corner.y, Point.distance(_corner,_corner2));
     addChild(CANVAS); 
    }
}

function liveDrag(e:MouseEvent):void{
    CANVAS.graphics.clear(); 
    CANVAS.graphics.lineStyle(0, 0x999999);

    _corner2 = new Point(e.stageX, e.stageY);
    //trace(Point.distance(_corner,_corner2).toFixed(2));
    CANVAS.graphics.drawCircle(_corner.x, _corner.y, Point.distance(_corner,_corner2));
    addChild(CANVAS); 
}
+2  A: 

If you add the MouseEvent.MOUSE_UP to the object that you are dragging, the event will only fire if the item is underneath the mouse at the moment the MOUSE_UP happens, but since you're updating the item with MOUSE_MOVE, that's a race-condition between when the MOUSE_UP happens and when the MOUSE_MOVE happens.

To avoid such problems you want to guarantee that you receive the MOUSE_UP whenever MOUSE_UP fires, during your live-update cycle. To do that, add the event listener to the stage just when it's needed, something like this:

menFront.addEventListener(MouseEvent.MOUSE_DOWN, setAnchor);

function setAnchor(event:MouseEvent):void
{
    stage.addEventListener(MouseEvent.MOUSE_UP, completeRect);
    // your other functionality
}

function completeRect(event:MouseEvent):void
{
    stage.removeEventListener(MouseEvent.MOUSE_UP, completeRect);
    // your other functionality
}

so that your completeRect doesn't get called inadvertently if you're clicking elsewhere.

Hope This Helps

alecmce
This might also be of interest: http://github.com/alecmce/as3geometry/blob/master/src/ui/interactive/DragMechanism.as
alecmce