2016-07-04 73 views
0

我想創建一個簡單的粒子模擬。有兩種類型的粒子靜態和移動。靜態粒子將運動粒子吸引到其中心。靜態顆粒具有規定它們是如何硬拉動移動的顆粒無法阻止粒子過沖

var angle:Number = Math.atan2(moving.y - static.y , moving.x - static.x); 
var dist = Point.distance(new Point(moving.x,moving.y) , new Point(static.x,static.y)); 

moving.velX += Math.cos(angle + Math.PI) * static.strength/dist; 
moving.velY += Math.sin(angle + Math.PI) * static.strength/dist; 

的問題是當顆粒只是路過的中心的距離是非常小的強度屬性,它導致非常大的速度值。

在計算速度之前,我添加了額外的距離檢查。

if (dist < 1) 
    dist = 1; 

但問題仍然存在。我不知道這個問題。

這裏是超調發生的快照。

enter image description here

回答

1

普通力場使用距離爲改性的廣場,你在這裏使用距離的單電,當然力場情況不同。您應該var dist線更改爲以下:

var dist:Number = (moving.x-static.x)*(moving.x-static.x) + (moving.y-static.y)*(moving.y-static.y); 

這樣dist將持有實際距離的平方,因此通過dist將會給你正確的力場配置。

而且,請將其重命名爲static,因爲它是AS3中的保留字。

+0

我在原始代碼中沒有使用'static'作爲變量名。 –

+0

@SayamQazi,檢查你的代碼,你有'static.x'和'static.y'。稱它爲'force',稱之爲'atttractor'或者其他只是不變的或類名變成與保留字相同的顏色。 –

+0

是的,我知道。我正在談論我的原始代碼。我沒有在SO上拷貝我的原始代碼。 –

2

在運行dist計算之前或運行vel計算之前,您可能會聲明dist值。相反,請確保您正在做的dist檢查在計算distvel之間。 Vesper也是正確的,爲了得到正確的力效應,它應該使用距離平方。但即使這樣做,你仍然可能會得到不理想的結果(儘管完全準確,數學上)。

var angle:Number = Math.atan2(moving.y - static.y , moving.x - static.x); 
var dist = Point.distance(new Point(moving.x,moving.y) , new Point(static.x,static.y)); 

if (dist < 1) dist = 1; // just make sure your constraint goes here. 

moving.velX += Math.cos(angle + Math.PI) * static.strength/dist/dist; // this uses dist squared 
moving.velY += Math.sin(angle + Math.PI) * static.strength/dist/dist; // but don't use this method in addition to Vesper's or you'll have dist to the power of 4. 
+0

是的,我在距離計算和更新速度部分之間進行了距離檢查。你說我可能還會得到不想要的結果,所以你可以給我一個解決方案。 –

+0

顯然Vesper解決了你的問題。你可以忽略我的建議。或者他的解決方案不起作用? –