1
votes

I am making a game in vb.net and I need to tell whether the character is colliding with any pictureboxes, when I add the "For Each PictureBox In Me.Controls" to the code it doesn't detect any collisions anymore here's the code :

For Each PictureBox In Me.Controls
    If Not Collision(picBox1, PictureBox) Then
        walk = 1
        tmrWalk.Start()
        picBox1.Top -= 5
    End If
Next

For some reason adding "For Each PictureBox In Me.Controls" also vastly speeds up the movement speed in that direction.

Collison is from a module, I know that collision works because I have tested it while specifying both the pictureboxes

1
What exactly is your problem? aren't you testing against all picutre boxes already?Eisenhorn
when I add the "For Each PictureBox In Me.Controls" to the code it doesn't detect any collisions anymoreomja.das
I see, I'll post some code in a second.Eisenhorn

1 Answers

0
votes

The problem might be that you're checking against the player himself, as he is part of all the picture boxes aswell, so you'll have to escape that case:

Dim colliding as Boolean = false
For Each pb as PictureBox In Me.Controls
    ' Dont test against the player
    If Not pb is picBox1
        ' Check for collision
        If Collision(picBox1, PictureBox) Then
            ' Player is colliding - dont walk!
            colliding = true
        End If
    End If
Next

If Not colliding Then
    walk = 1
    tmrWalk.Start()
    picBox1.Top -= 5
End If

So now if a collision happens, we keep track of that, and only allow movement if no collision happened at all.

Edit Generally you should test for a collision BEFORE you move, so that you actually only move your character if you know that no collision will be happening.

If you decide to handle collisions after movement, you'll have cache the coordinates of yoru player before movement and then - in case of a collision - reset its coordinates to the saved values.

You might want to read up on collision handling in game development, there's tons of good tutorials out there that will get you going and also display a better solution than I have presented here.