2017-02-03 90 views
2

我在我的遊戲中2D碰撞檢測有點麻煩。
問題是我的播放器的矩形沒有正確註冊與其他對象矩形的交集。MonoGame碰撞檢測矩形的起源

我想知道如果我用來旋轉我的播放器的原始變量與我的問題有什麼關係以及如何修復它。

我會更詳細地解釋問題,但這裏是我的代碼第一: 注意:原點類型爲Vector2,角度類型爲float,所有碰撞矩形都是Rectangle類型。

//Player.Update method 

     //origin needs to be in update, because position of source changes for every frame of animation 
     origin = new Vector2(Width/2, Height/2); 
     playerDirection = new Vector2((float)Math.Sin(angle), (float)Math.Cos(angle)); 

     //Updating the position of my collision rectangle 
     collisionRect.X = (int)position.X; 
     collisionRect.Y = (int)position.Y; 

     //Changing the values of angle while key is pressed 
     if (Keyboard.GetState().IsKeyDown(Keys.A)) 
     { 
      angle -= 0.05f; 
     } 

     if (Keyboard.GetState().IsKeyDown(Keys.D)) 
     { 
      angle += 0.05f; 
     } 
     //Updating player's position 
     if (Keyboard.GetState().IsKeyUp(Keys.X)) 
     { 
      keyPress = false; 
     } 

     if (Keyboard.GetState().IsKeyDown(Keys.W)) 
     { 
      position -= playerDirection * Speed; 
     } 

     if (Keyboard.GetState().IsKeyDown(Keys.S)) 
      position += playerDirection * Speed; 
     //Checking for collision detection with background objects 
     if(BackgroundMaker.collisionPositions.Count >= 1) 
     { 
      foreach(Rectangle colPos in BackgroundMaker.collisionPositions) 
      { 
       if(collisionRect.Intersects(colPos)) 
       { 
        if (collisionRect.X < colPos.Right) 
         position.X = colPos.Right; 
       } 
      } 
     } 
    } 
} 

這段代碼的問題在於,我的玩家在他半途中只碰到牆。我還沒有實現右側,上下兩側的碰撞,只是左側。

這裏是什麼樣子: enter image description here

在此先感謝的人誰可以幫我回答這個問題。 如果您需要更多信息,請告訴我。

+0

我會建議有您畫碰撞盒玩家調試模式,那麼它會變得更加明顯發生了什麼 – Ben

+0

碰撞矩形的大小是多少? – Ben

+1

@Ben矩形的大小是32x32,它是字符精靈的寬度和高度的大小。 –

回答

2

您的代碼工作,你如何指示

if (collisionRect.X < colPos.Right) 
    position.X = colPos.Right; 

在這裏,你正在檢查,如果碰撞箱的中間是小於該對象的右側,然後設置玩家中間位置在對象的右側,因此玩家的中間不能比它正在交叉的對象更遠。

然而,這是不考慮玩家寬度

您需要調整您的代碼的工作更是這樣的:

float halfWidth = 16.0f; // ideally add a width to the player class and divide by 2 
if (collisionRect.X - halfWidth < colPos.Right) 
    position.X = colPos.Right + halfWidth; 
+1

感謝您的回答!我不知道x和y座標對應於精靈的中間。我確定它們對應於左上角,所以矩形將與它一起創建 –