views:

28

answers:

2

Hi,

I'm trying to so the following in AS3. I have an object that I would like to behave as follows:

  1. When you click and drag with the mouse, it gets dragged along, constrained to the x axis (left and right only).

  2. When the mouse button is the released the object keeps going at that speed and direction, the slows to a stop. If the unpressed mouse is the moved, the object DOES NOT change direction to follow the mouse.

  3. The object does not respond to or in any way follow the unpressed mouse; all it does it come to a stop when the mouse is released, as described above.

Seems like a simple thing but I've been looking for the answer for days. Some people have made suggestions but the don't behave the way I like.

Thanks in advance!

A: 

I'm not too familiar with AS3, but here's a simple way to do it.

I assume your object already stores an x coordinate (I'll call it object.x). Add a property "v" (for velocity) to your object and make it 0, and add property "mass", which can be 1 if you just want the object to snap to the mouse. When the object is clicked, call the following code:

var animLoopID:uint = setInterval(function():void {
    // this will run every 100ms in order to animate the object
    // and will stop once the mouse is raised and the object has come to rest

    // if the mouse is still down, we want the object to follow it
    // i don't know the right syntax for this, but this should give you an idea
    if (mouseDown) {
        object.v = (mouseX - object.x)/object.mass;

        // if you make this object.v += ..., the object will
        // oscillate around the mouse instead of snapping to it
        // and you'll have to increase your mass accordingly
        // to keep it from slinging around wildly
    }
    else if (Math.abs(object.v) > 0.0001) { // 0.0001 to avoid rounding errors
        object.x += object.v;
        object.v *= 0.95; // friction -- the closer to 1, the less friction

        // you may also consider doing some bounds-checking on x here
    }
    else {
        // the mouse isn't dragging and the object is at rest...we're done :)
        clearInterval(animLoopID);
    }
}, 100);

I have no idea how good an idea it is to do this in AS3, but it's a start, I suppose. It's not entirely correct from a physical perspective either...I really should look up the equations of motion and write a proper solution.

Faisal
A: 

I've found an grat online tutorial that has the answer. I was a matter of tinkering with the code. The writer even has .fla files for download.

http://www.quasiuseful.com/?id=11

Maria