Search code examples
actionscript-3

How to set drag X limit


I'm working on some draggable/droppable bar.So it's draggable only x because this is select bar.Problem is select button draggable out of stage limit. I want to draggable only in stage limit.I tried some methods hitTestPoint and newshape but it didn't work.

// define lock on y-axis
var LOCKY:Number = secbuton.y;
 
stage.addEventListener(MouseEvent.MOUSE_MOVE, _mouseMove);
function _mouseMove(e:MouseEvent):void
{
if(secbuton.y != LOCKY) secbuton.y = LOCKY;
}
 
// dragging
secbuton.addEventListener(MouseEvent.MOUSE_DOWN, _mouseDown);
function _mouseDown(e:MouseEvent):void
{
secbuton.startDrag(false, new Rectangle(35,345,420));
secbuton.addEventListener(MouseEvent.MOUSE_UP, _mouseUp);
}
 
// dropping
function _mouseUp(e:MouseEvent):void
{
secbuton.stopDrag();
secbuton.removeEventListener(MouseEvent.MOUSE_UP, _mouseUp);

            if(secbuton.hitTestObject(kose1)){
    secbuton.x = levcbk1.x +5  
    }

    if(secbuton.hitTestObject(lev2)){
    secbuton.x = levcbk2.x +5  
    }
 if(secbuton.hitTestObject(lev3)){
    secbuton.x = levcbk3.x +5
    }
                 if(secbuton.hitTestObject(lev4)){
    secbuton.x = levcbk4.x +5
    }

                         if(secbuton.hitTestObject(lev5)){
    secbuton.x = levcbk5.x +5
    }
}

UPDATE

Normally bar work like this.

[![enter image description here][1]][1]

But problem is there when hit the borders or when try drag to y axis.

[![enter image description here][2]][2]


Solution

  • Don't use MOUSE_LEAVE. Use MOUSE_UP but on stage object - MOUSE_UP is dispatched by stage object even it you release button outside the flash player window (basically anywhere)

    So simply change those lines

    secbuton.addEventListener(MouseEvent.MOUSE_UP, _mouseUp);
    secbuton.removeEventListener(MouseEvent.MOUSE_UP, _mouseUp);
    

    to this:

    stage.addEventListener(MouseEvent.MOUSE_UP, _mouseUp);
    stage.removeEventListener(MouseEvent.MOUSE_UP, _mouseUp);
    

    And as Organis said. Rectangle parameters are x , y , width and height. So from what I see on the gifs you want set it to:

    secbuton.startDrag(false, new Rectangle(35,345,420-35,0));

    If you set rectangle heigh to 0, your object will be locked on y-axis (345 in your case) so you don't need to use the LOCKY variable and move listener.