VB.NET collision between pictureboxes

て烟熏妆下的殇ゞ 提交于 2019-12-02 01:30:44

问题


I'm trying to make a simple game and i need to know if picturebox1( my character) collides with other pictureboxes ( the walls).

I have already worked out how do this but it only works with my character and 1 other picturebox for example:

If picturebox1.bounds.intersectWith(picturebox2.bounds) then
   collision = true
end if

I tried to do something else like this:

For Each PictureBox In Me.Controls
  If PictureBox1.Bounds.IntersectsWith(PictureBox.Bounds) Then
     collision = True
  Else : collision = False
  End If
Next

But then the boolean collision would always be true because picturebox1 (the character) always intersects with itself.

So i changed the picturebox into a panel and the code looks the following:

For Each PictureBox In Me.Controls
  If Panel1.Bounds.IntersectsWith(PictureBox.Bounds) Then
     collision = True
  Else : collision = False
  End If
Next

But it only works with 1 single picture box and not with all the pictureboxes in the form. I don't understand why... And if anyone maybe knows how to add an exception in the for each function so i can keep my picturebox1

something like this maybe

For each picturebox(except(picturebox1)) in me.controls

because i've searched for that but didn't find anything...

Any help is greatly appreciated :) Thanks!


回答1:


One way of doing it:

For Each PictureBox In Me.Controls
  If PictureBox IsNot PictureBox1 AndAlso PictureBox1.Bounds.IntersectsWith(PictureBox.Bounds) Then
     collision = True
     Exit For 'Exit when at least one collision found 
  Else : collision = False
  End If
Next

This would set collision to False if PictureBox is indeed PictureBox1. But note that you are overwriting the collision state in each loop, which not what you really want. You should exit the for loop when one collision is found (see my code). You may also change your code like this :

collision = False
For Each PictureBox In Me.Controls
  If PictureBox IsNot PictureBox1 AndAlso PictureBox1.Bounds.IntersectsWith(PictureBox.Bounds) Then
     collision = True
     Exit For
  End If
Next


来源:https://stackoverflow.com/questions/15311255/vb-net-collision-between-pictureboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!