2014-10-17 67 views
1

我已經創建了兩個矩形,可以隨其中一個移動並跳起,另一個靜止在窗體上作爲障礙物。 我希望障礙物作爲障礙物(或者牆壁,如果你願意的話),基本上我想讓活動矩形在其右側碰撞障礙物左側(等等)時停止。二維矩形在碰撞時應該停止移動

我發現這個代碼如何檢測碰撞(因爲它顯然更容易不進行碰撞檢測)的一篇文章中兩個矩形之間:

OutsideBottom = Rect1.Bottom < Rect2.Top 
OutsideTop = Rect1.Top > Rect2.Bottom 
OutsideLeft = Rect1.Left > Rect2.Right 
OutsideRight = Rect1.Right < Rect2.Left 
//or 
return NOT (
(Rect1.Bottom < Rect2.Top) OR 
(Rect1.Top > Rect2.Bottom) OR 
(Rect1.Left > Rect2.Right) OR 
(Rect1.Right < Rect2.Left)) 

但我不知道如何實現它。我有一個名爲「player1.left」的bool,當我按下鍵盤上的'A'('D'向右移動,'W'跳轉)時,它變爲true,當true時將矩形移動10個像素到(在Timer_Tick事件中)。

編輯:

「rect1.IntersectsWith(RECT2)」 的作品來檢測碰撞。但是如果我想讓可移動的矩形停止向右移動(但仍然能夠跳躍並移動到左側),如果它的右側與障礙左側碰撞,我將如何使用它(if語句中應該包含的內容)方(等等)?

+4

在那個Rectangle實現中有一個'Rectangle.Intersects()'方法嗎?如果是這樣:'bool collided = rect1.Intersects(rect2);' – itsme86 2014-10-17 15:03:23

+0

「,因爲它顯然更容易檢測不到碰撞」。不會說這更容易,但更快。它停止檢查其餘的值。更快速地連續檢查每個更新的1個條件與4. – TyCobb 2014-10-17 15:26:55

回答

1

// UPDATE 假設您有從Rectangle繼承的PlayableCharacter類。

public class PlayableCharacter:Rectangle { 

    //position in a cartesian space 
    private int _cartesianPositionX; 
    private int _cartesianPositionY; 

    //attributes of a rectangle 
    private int _characterWidth; 
    private int _characterHeight; 

    private bool _stopMoving=false; 


    public PlayableCharacter(int x, int y, int width, int height) 
    { 
     this._cartesianPositionX=x; 
     this._cartesianPositionY=y; 
     this._chacterWidth=width; 
     this._characterHeight=height; 
    } 

    public bool DetectCollision(PlayableCharacter pc, PlayableCharacter obstacle) 
    { 

    // this a test in your method 
     int x=10; 
     if (pc.IntersectsWith(obstacle)){ 
      Console.Writeline("The rectangles touched"); 
      _stopMoving=true; 
      ChangeMovingDirection(x); 
      StopMoving(x); 
     } 

    } 

    private void ChangeMovingDirection(int x) 
    { 
    x*=-1; 
    cartesianPositionX+=x; 
    } 


    private void StopMoving(int x) 
    { 

    x=0; 
    cartesianPositionX+=x; 
    } 

}

在代碼I`ve給你,在一個情況,當角色是要正確的,這是肯定的x值,該角色會面對另一個方向。如果他在左邊移動,如果他碰到障礙物,他將面對另一個方向。

使用StopMoving,即使您製作的腳本隨時間在循環中運行,但它不會讓角色移動。

我認爲這應該爲您的工作奠定基礎。如果有任何問題,請對我寫的解決方案發表評論,我會盡我所能幫助你,如果它在我的範圍內。

+0

@ Anders23通常,當您使對象移動時,這是因爲您正在修改其位置的像素值。當你使用我的代碼時,你可以停止這個過程。 – 2014-10-17 15:47:25

+0

如果我想要可移動矩形停止向右移動(但仍然能夠跳躍並移動到左側),代碼將如何顯示(如果其右側與障礙物左側碰撞)(等等)? – Anders23 2014-10-17 16:09:19

+0

如果提供的答案以任何方式幫助您,或者實際上您是在尋找答案,請將其標記爲答案,以便其他人在未來知道! :) @ Anders23 – 2014-10-19 00:57:03