2012-11-14 20 views
1

下面的代碼從物理引擎中獲取對象的所有位置和角度,並相應地更新每個對象。一旦對象之間有很多活動,它就會減慢速度。移動許多畫布對象的高效方法

我知道它是不是物理引擎,因爲我有使用OpenGL編寫的完全相同的東西,但是我不能將它用於我的特定應用程序。

int bodyId = 0; 
foreach (Shape shape in shapes) 
{ 
    //Don't update sleeping objects because they are sleeping. 
    //Waking them up would be terrible... 
    //IGNORE THEM AT ALL COSTS!! 
    if (physics.IsSleeping(bodyId)) 
    { 
     ++bodyId; 
     continue; 
    } 

    //Rotate transform 
    RotateTransform rot = new RotateTransform(physics.GetAngle(bodyId)); 
    rot.CenterX = shape.Width/2; 
    rot.CenterY = shape.Height/2; 

    //Set the shape to rotate 
    shape.RenderTransform = rot; 

    //Body position 
    Point bodyPos = physics.GetPosition(bodyId); 
    Canvas.SetLeft(shape, bodyPos.X - shape.Width/2); 
    Canvas.SetTop(shape, bodyPos.Y - shape.Height/2); 

    ++bodyId; 
} 

我想知道是否有在做上述更有效的方式,分解成幾個問題。

  1. 如果我打電話Canvas.SetLeft和Canvas.SetTop是有過一段時間的UI將啓動循環內渲染?或者如果不清楚,Canvas.SetLeft和Canvas.SetTop函數的工作原理是什麼?

  2. 因爲我已經使用了RotateTransform,所以使用TranslateTransform會更好嗎?

回答

1
  1. 是,機頂盒()和SetLeft()被稱爲爲你的每一個元素每次。如果你想讓一切更有效率,我會做以下事情。首先使用更新邏輯的更新函數,即計算對象的位置,然後通過循環遍歷對象來處理圖形,並且只使用setLeft()和setTop()一次而不是每次更新。
  2. 是的,它會爲您節省一次手術。

也許還有別的東西可以優化。您可以通過將當前旋轉狀態保存在形狀對象中來節省大量的計算能力,而不是像RotateTransform()這樣佔用CPU密集型的矩陣操作。同樣使用矢量可能會幫助您提高性能。