Songman Yi
Songman Yi

Reputation: 13

How do you check if a picturebox is touching a picturebox that is in a certain array?

I have a list of pictureboxes named slimeList. I have it so that the pictureboxes in slimeList move around the screen. I have a timer on the Form, an on each tick, I want to check for each element of slimeList if it is touching another element of slimeList. The code snippet below shows how the pictureboxes of slimelist are moving around:

For Each obj In slimeList
            If DistanceBtwn(obj.Location, MouseFollower.Location) > 2 Then
                Randomize()
                Glide(obj, MouseFollower.Location, CInt(Math.Floor(4 * Rnd())) + 1)
            End If
Next obj

As you can see here, the pictureboxes in slimeList are following something called the MouseFollower. I want to make another for loop like this:

For Each obj In slimeList
            If obj [is touching a picturebox which is in slimeList] Then
                [expression]
            End If
Next obj

Upvotes: 1

Views: 420

Answers (1)

Sam Axe
Sam Axe

Reputation: 33738

The System.Windows.Forms.PictureBox class defines the Bounds property with is a System.Drawing.Rectangle. Rectangles can figure out if they are touching another rectangle with the .IntersectsWith method.

'  Check that the list is not nothing and contains more than 1 element before continuing.
  For outerIndex As Int32 = 0 To slimeList.Count - 2
      For innerIndex As Int32 = outerIndex + 1 To slimeList.Count - 1
          If slimeList(outerIndex).Bounds.IntersectsWith( slimeList(innerIndex).Bounds ) Then
              ' slimeList(outerIndex) and slimeList(innerIndex) have collided.
          End If
      Next
  Next

Upvotes: 1

Related Questions