2010-07-02 41 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,但它是一個開始怎麼好,我想。從物理角度來看,這不完全正確......我真的應該查找運動方程並寫出適當的解決方案。