2010-07-02 56 views
0

我试图在AS3中如此处理。我有一个对象,我想表现如下:在AS3中,对象被拖动并释放时呈现惯性

  1. 当您单击并拖动鼠标,它就会被拖着,受限于x轴(左,右只)。

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

  3. 该对象不响应或以任何方式跟随未压缩的鼠标;如上所述,当鼠标被释放时,所有这一切都会停止。

看起来像一个简单的事情,但我一直在寻找答案的日子。有些人提出了建议,但并不表现出我喜欢的方式。

在此先感谢!

回答

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,但它是一个开始怎么好,我想。从物理角度来看,这不完全正确......我真的应该查找运动方程并写出适当的解决方案。