2010-08-22 41 views
1

我有一個碰撞檢測類,通過查找中心之間的距離以及該距離是否足夠小而成爲碰撞來工作(請參閱Collision Detection error)。我的問題是試圖使這個實際工作,橢圓相互碰撞。如有必要,我會解釋更多。 THX碰撞檢測實現

+0

誰做指定橢圓的位置(旋轉等)?還是你的意思是圈子? – raisyn 2010-08-22 08:00:49

回答

2

最好的辦法時,圖像重疊,您可以在以下鏈接

http://www.codeproject.com/KB/game/collision3.aspx

Per-pixel collision problem in C#

我也做了一個問題,瞭解更多關於這個每個像素碰撞檢測來實現像幾年前的一個項目,當我需要檢測兩個圓圈是否重疊時,我使用以下代碼

public static bool Intersect(Rectangle rectangle1, Rectangle rectangle2) 
    { 
     if (((rectangle1.X < (rectangle2.X + rectangle2.Width)) && (rectangle2.X < (rectangle1.X + rectangle1.Width))) && (rectangle1.Y < (rectangle2.Y + rectangle2.Height)) && (rectangle2.Y < (rectangle1.Y + rectangle1.Height))) 
     { 
      Vector2 rect1Centre = new Vector2(rectangle1.X + rectangle1.Width/2, rectangle1.Y + rectangle1.Height/2); 
      Vector2 rect2Centre = new Vector2(rectangle2.X + rectangle2.Width/2, rectangle2.Y + rectangle1.Height/2); 
      double radius1 = ((rectangle1.Width/2) + (rectangle1.Height/2))/2; 
      double radius2 = ((rectangle2.Width/2) + (rectangle2.Height/2))/2; 

      double widthTri = rect1Centre.X - rect2Centre.X; 
      double heightTri = rect1Centre.Y - rect2Centre.Y; 
      double distance = Math.Sqrt(Math.Pow(widthTri, 2) + Math.Pow(heightTri, 2)); 

      if (distance <= (radius1 + radius2)) 
       return true; 
     } 
     return false; 
    } 

不是很好的代碼,但我寫它做我的第一個XNA遊戲

+0

rectangle1.X是矩形中心的X座標,rectangle1.Y是Y座標 – 2010-08-22 10:53:33

+0

乾杯人,但我怎樣才能使它適用於現有的對象,而不是由方法創建的? – Apophis 2010-08-23 04:05:46

+0

@NeoHaxxor我真的要看你有多少物品,我只有3個圈子(這是一個空氣曲棍球遊戲),所以我每次都有一個事件處理程序,每次移動時我都會對其他矩形進行檢查。如果你有很多需要檢查的對象,可能有更好的方法。 – 2010-08-23 10:44:58

2

我最近有同樣的問題。圓圈重疊很容易確定。使用省略號更加棘手,但並不那麼糟糕。你玩橢圓方程一段時間,結果出現:

//Returns true if the pixel is inside the ellipse 
public bool CollisionCheckPixelInEllipse(Coords pixel, Coords center, UInt16 radiusX, UInt16 radiusY) 
{ 
    Int32 asquare = radiusX * radiusX; 
    Int32 bsquare = radiusY * radiusY; 
    return ((pixel.X-center.X)*(pixel.X-center.X)*bsquare + (pixel.Y-center.Y)*(pixel.Y-center.Y)*asquare) < (asquare*bsquare); 
} 

// returns true if the two ellipses overlap 
private bool CollisionCheckEllipses(Coords center1, UInt16 radius1X, UInt16 radius1Y, Coords center2, UInt16 radius2X, UInt16 radius2Y) 
{ 
    UInt16 radiusSumX = (UInt16) (radius1X + radius2X); 
    UInt16 radiusSumY = (UInt16) (radius1Y + radius2Y); 

    return CollisionCheckPixelInEllipse(center1, center2, radiusSumX, radiusSumY); 
} 
+0

乾杯的人。還有一件事 - 能夠使該方法觸發translatetransform方法?代碼的細節不是問題,我編碼它,只是讓上面的代碼返回true並觸發此代碼。謝謝 – Apophis 2010-08-23 04:34:12