PDA

View Full Version : constrain startDrag horizontally


PJjerry
12-02-2007, 02:14 AM
So I have a Sprite and if using startDrag(), how do I constrain the movement to x-axis only? that is, move it horizontally?

The free x,y movement code sample is here, directly from Adobe's livedocs:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Sprite.html#includeExamplesSummary

ivanparas
12-02-2007, 05:37 AM
I would either add or append to an ENTER_FRAME listener that gets the Y value of the object when you click it (or a predefined value) and then have it constantly checked and set to that value while being dragged.

ivanparas
12-02-2007, 07:31 AM
Here is some code I wrote to demonstrate:


var box:Sprite = new Sprite();
var boxX:Number = new Number;

drawBox();

function drawBox():void
{

box.graphics.beginFill(0x123456);
box.graphics.drawRect(100, 100, 100, 100);
box.graphics.endFill();

stage.addChild(box);

box.addEventListener(MouseEvent.MOUSE_DOWN, dragMe)
stage.addEventListener(MouseEvent.MOUSE_UP, dropMe)
stage.addEventListener(MouseEvent.MOUSE_MOVE, keepX)

function dragMe(event:MouseEvent):void
{
box.startDrag();
boxX = box.x;
keepX(event);
}

function dropMe(event:MouseEvent):void
{
box.stopDrag();
}

stage.removeEventListener(Event.ENTER_FRAME, drawBox);
}

function keepX(event:MouseEvent)
{
box.x = boxX;
}


Using startDrag() makes it a bit jittery if you drag the box side to side. The ideal thing to do would to just make a custom dragging script that only applied to the X.

Mazoonist
12-02-2007, 12:39 PM
The second parameter of startDrag is a rectangle. By just creating a rectangle object, you can constrain the movement to whatever area you want. To constrain it so that it only drags along the x axis, set the height of the rectangle (the last parameter) to 0. Paste this code in frame 1 of a new fla and try it out:
var ball:MovieClip = new MovieClip();

ball.graphics.lineStyle(2);
ball.graphics.beginFill(0xFF0000);
ball.graphics.drawCircle(100, 100, 15);
ball.buttonMode = true;
addChild(ball);

var rect:Rectangle = new Rectangle(ball.x, ball.y, ball.x + 350, 0);

ball.addEventListener(MouseEvent.MOUSE_DOWN, downHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, upHandler);

function downHandler(event:MouseEvent) {
ball.startDrag(false, rect);
}
function upHandler(event:MouseEvent){
ball.stopDrag();
}

PJjerry
12-02-2007, 02:13 PM
Thanks both of you!

I did consider the rectangle param before but for some reason(I was dumb) I thought once the y is set to zero, you can only drag upon a horizontal "line" :eek:

Since you point it out I just try the code.... it works perfectly :D