2015-12-18 122 views
0

我已經重新做了幾次,但我無法得到它的工作......它檢測到當按鈕1位於較低和/或最右側部分BUTTON2,但如果它在上和/或最左邊的一部分... ...會很高興知道是什麼問題,因爲我吸在調試......在簡單測試「遊戲」中失敗的碰撞檢測

if (
    (
     (button1.Top >= button2.Top && button1.Top <= (button2.Top + button2.Height)) 
     || (button1.Bottom >= button2.Bottom && button1.Bottom <= (button2.Bottom + button2.Height)) 
    ) 
    && 
    (
     (button1.Left >= button2.Left && button1.Left <= (button2.Left + button2.Width)) 
     || (button1.Right >= button2.Right && button1.Right <= (button2.Right + button2.Width)) 
    ) 
) 
+0

確實有你喜歡的代碼是可以的,但如果你要求幫助,讓別人更容易閱讀是有道理的。 – mlusiak

+0

謝謝!我實際上並不知道這是寫它的一種合法方式,但是當我考慮它時,這很明顯:D –

回答

0

我這樣做,它工作得很好。它基本上只是檢查左上角是否在另一個按鈕的位置。棘手的部分是僅僅增加在其基本上由大小抵消了按鈕1使其成爲這樣的位置將比BUTTON2的更大的第二比較的寬度和高度,如果它是與在BUTTON2

if ((button1.Location.X > button2.Location.X && button1.Location.Y > button2.Location.Y) 
      ||(button1.Location.X + button1.Size.Width > button2.Location.X 
      && button1.Location.Y + button1.Size.Height > button2.Location.Y)) 
      MessageBox.Show("In side other button"); 

但是如果要做到這一點,你可以做到這一點

if(button1.Bounds.IntersectsWith(button2.Bounds)) 
    MessageBox.Show("Within button"); 

這將做你想要做的比較更簡單的方法。

+0

非常感謝!但是,有一個問題是窗口0,0或左下角的左上像素? :D再次感謝! :D –

+0

左上角是0,0。 –

+0

哇......如果我從一開始就知道我現在就完成了......我想我應該在下次更接近地尋找答案,而不是讓它做出來無緣無故的太複雜....:D非常感謝! :d –

0

看起來問題出在在這裏:

(button1.Bottom >= button2.Bottom && button1.Bottom <= (button2.Bottom + button2.Height)) 

這大概是想看看是否button1的底部是內部button2,所以它應該與button2.Topbutton2.Top + button2.Height進行比較。

可能有與button1.Right類似的問題。

+0

我明白你的意思了,但我儘管.Top是從頂端開始的dist。底部是從底部dist,所以我不認爲它會工作,以比較他們對對方...我可能是錯誤的,但.. .. D –