2014-01-18 25 views
1

我已經定義DispatcherTimer(每毫秒蜱1)。還有我收集的矩形和方法來檢查碰撞。如何檢查在收集衝突(相互每個元素)

public List<Rectangle> Cars { get; set; } 
int time = 0; 

_timer = new DispatcherTimer(); 
_timer.Interval = new TimeSpan(0, 0, 0, 0, 1); 
_timer.Tick += _timer_Tick; 
_timer.Start(); 

void _timer_Tick(object sender, EventArgs e) 
{ 
    foreach(Rectangle r in Cars) 
    { 
     r.Move() 
    } 
} 

public bool CheckCollision(Rectangle r1, Rectangle r2) 
{ 
    bool result = false; 
    Rect rect1 = new Rect((double)r1.GetValue(Canvas.LeftProperty),(double)r1.GetValue(Canvas.TopProperty), r1.Width, r1.Height); 
    Rect rect2 = new Rect((double)r2.GetValue(Canvas.LeftProperty), (double)r2.GetValue(Canvas.TopProperty), r2.Width, r2.Height); 

    if (rect1.IntersectsWith(rect2)) 
    { 
     result = true; 
    } 
    else 
    { 
     result = false; 
    } 

    return result; 
} 

問題是如何(蜱)具有衝突方法(或任何其他方式)檢查在保藏每個對象彼此交互並且例如停止該對象移動(同時collised)。 任何想法或代碼都會很棒。謝謝。

回答

1

你可以試試:

 foreach(Rectangle r in Cars.Where(c1 => Cars.All(c2 => !CheckCollision(c1,c2)))) 
      r.Move();