在AS3中,物体被拖动,当释放时它表现出惯性

时间:2010-07-02 20:50:37

标签: actionscript-3

我正在尝试AS3中的以下内容。我有一个对象,我想表现如下:

  1. 使用鼠标单击并拖动时,它会被拖动,约束到x轴(仅限左右)。

  2. 当释放鼠标按钮时,对象继续以该速度和方向行进,减速停止。如果移动了未按下的鼠标,则该对象不会改变方向以跟随鼠标。

  3. 对象不响应或以任何方式跟随未压缩的鼠标;如上所述,释放鼠标时它会停止。

  4. 看起来似乎很简单,但我一直在寻找答案。有些人提出了建议,但不按我喜欢的方式行事。

    提前致谢!

2 个答案:

答案 0 :(得分:0)

我对AS3不太熟悉,但这是一种简单的方法。

我假设你的对象已经存储了一个x坐标(我称之为object.x)。为对象添加属性“v”(对于速度)并使其为0,并添加属性“mass”,如果您只想让对象捕捉到鼠标,则可以为1。单击对象时,请调用以下代码:

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);

我不知道在AS3中做这个有多好,但我认为这是一个开始。从物理角度来看,它也不完全正确......我真的应该查看运动方程并写出适当的解决方案。

答案 1 :(得分:0)

我找到了一个有答案的grat在线教程。我是修补代码的问题。作者甚至有.fla文件供下载。

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