Skip to main content
New Participant
July 1, 2010
Question

AS3 Dragging with inertia for dummies

  • July 1, 2010
  • 1 reply
  • 2367 views

Hi,

I'm trying to achieve a fairly simple effect--a dragging a MC with inertia.

Specifically, I'm trying to get this to happen:

1. When you click with the mouse on the MC (not the entire stage), the MC gets dragged along.

2. When you let go of the mouse button, the MC keeps going with inertia (slowly comes to a stop) that depends on the speed with which the MC was dragged and in the same direction. The MC shouldn't change directions if the unpressed mouse is moved around.

3. The dragging is constricted to the X axis.

Thanks!

This topic has been closed for replies.

1 reply

Inspiring
July 1, 2010

Your best bet is to use a tween engine (like TweenLite) in combination with MouseMove event handling.

Also, there are some tutorials on Flash physics that show math to create elastic motions.

In any case math will be involved.

New Participant
July 1, 2010

Could someone give me a bit of direction? I'm sure I can find an inertia physics formula, but I don't know how to capture the mouse speed during the Mouse Down with Mouse Move, in order to use it with Mouse Up, and how to make it so that, when Mouse Up, the thing comes to a stop but the doesn't move again until I press the mouse again.

For example, this script has many problems, such as the fact the the MC keeps following the mouse even in the mouse isn't pressed.

myMC.addEventListener(MouseEvent.MOUSE_DOWN, whenMouseDown);

myMC.addEventListener(MouseEvent.MOUSE_UP, whenMouseUp);


function whenMouseDown(evt:MouseEvent):void {

     myMC.addEventListener(MouseEvent.MOUSE_MOVE, whenMouseMove);

     function whenMouseMove(evt:MouseEvent):void {

          myMC.x = mouseX; // placeholder dragging action

          // capture mouse speed?

     }

}


function whenMouseUp(evt:MouseEvent):void {

myMC.removeEventListener(MouseEvent.MOUSE_DOWN, whenMouseDown);

// add inertia here?

}

Also, how can I make the MC be dragged along with the without its X snapping to mouseX? Other stuff I tried here didn't work either?

Inspiring
July 1, 2010

I don't have much time for a detailed answer now but here are few things:

1. Never use nested functions - they are big trouble.

2. MOUSE_UP event listener should be added to stage - not the object.

3. Speed is a function of distance and time. So speed will be distance of mouse move divided by time over which this move occurred.

4. Object repositioning for your needs is not going to be according to mouseX but delegated to either tween or your custom calculations based on speed, etc.