Question

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!

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top