2010-04-28 34 views
2

所以我只是在做一個使用拉斐爾JS的基本軌道模擬器,在這裏我畫了一個圓作爲「星」,另一個圓作爲「星球」。它似乎工作得很好,隨着仿真的繼續,它的幀率逐漸減慢,直到軌道運動不再顯得流暢。下面的代碼(注意:用了jQuery只初始化頁面):爲什麼拉斐爾的幀率在這段代碼上變慢了?

$(function() { 
    var paper = Raphael(document.getElementById('canvas'), 640, 480); 
    var star = paper.circle(320, 240, 10); 
    var planet = paper.circle(320, 150, 5); 
    var starVelocity = [0,0]; 
    var planetVelocity = [20.42,0]; 
    var starMass = 3.08e22; 
    var planetMass = 3.303e26; 
    var gravConstant = 1.034e-18; 
    function calculateOrbit() { 
     var accx = 0; 
     var accy = 0; 
     accx = (gravConstant * starMass * ((star.attr('cx') - planet.attr('cx'))))/(Math.pow(circleDistance(), 3)); 
     accy = (gravConstant * starMass * ((star.attr('cy') - planet.attr('cy'))))/(Math.pow(circleDistance(), 3)); 
     planetVelocity[0] += accx; 
     planetVelocity[1] += accy; 
     planet.animate({cx: planet.attr('cx') + planetVelocity[0], cy: planet.attr('cy') + planetVelocity[1]}, 150, calculateOrbit); 
     paper.circle(planet.attr('cx'), planet.attr('cy'), 1); // added to 'trace' orbit 
    } 
    function circleDistance() { 
     return (Math.sqrt(Math.pow(star.attr('cx') - planet.attr('cx'), 2) + Math.pow(star.attr('cy') - planet.attr('cy'), 2))); 
    } 
    calculateOrbit(); 
}); 

它不會出現,我反正,那該代碼的任何部分會導致動畫逐漸減速到爬行,所以任何幫助解決問題將不勝感激!

+0

我對這個問題尋找答案,爲什麼我的小拉斐爾小部件去的時候我並沒有真正改變了什麼東西可怕的慢。我只插入jQuery,並使用jQuery選擇器而不是document.getElementById()調用來訪問各個小部件。在我看來,當與Raphael結合使用時,jQuery可以嚴重減慢速度。 – 2010-08-02 11:49:35

+0

現在你可以使用在Raphael中添加的'前夕'對象來改善這一點,然後你可以在每一幀獲得一個更新,然後在那裏做你的計算,所以我會讓planet.animate與另一個函數一起進行計算。 – Neil 2012-02-20 13:42:46

回答

3

問題在於回調您的planet.animate()調用中的calculateOrbit。它沒有正確處理raphael並導致內存泄漏或執行速度減慢。如果你有

setInterval(calculateOrbit, 150); 

將其刪除並替換線

calculateOrbit() 

應該平穩運行。

全碼:

$(function() { 
var paper = Raphael(document.getElementById('canvas'), 640, 480); 
var star = paper.circle(320, 240, 10); 
var planet = paper.circle(320, 150, 5); 
var starVelocity = [0,0]; 
var planetVelocity = [20.42,0]; 
var starMass = 3.08e22; 
var planetMass = 3.303e26; 
var gravConstant = 1.034e-18; 
function calculateOrbit() { 
    var accx = 0; 
    var accy = 0; 
    accx = (gravConstant * starMass * ((star.attr('cx') - planet.attr('cx'))))/(Math.pow(circleDistance(), 3)); 
    accy = (gravConstant * starMass * ((star.attr('cy') - planet.attr('cy'))))/(Math.pow(circleDistance(), 3)); 
    planetVelocity[0] += accx; 
    planetVelocity[1] += accy; 
    planet.animate({cx: planet.attr('cx') + planetVelocity[0], cy: planet.attr('cy') + planetVelocity[1]}, 150); 
    paper.circle(planet.attr('cx'), planet.attr('cy'), 1); // added to 'trace' orbit 
} 
function circleDistance() { 
    return (Math.sqrt(Math.pow(star.attr('cx') - planet.attr('cx'), 2) + Math.pow(star.attr('cy') - planet.attr('cy'), 2))); 
} 
setInterval(calculateOrbit, 150); 
}); 
+2

我有類似的問題,並希望嘗試此解決方案。我可以問一下,在你打給setInterval的電話中,150毫秒來自哪裏? – Doug 2014-05-22 22:25:12