VB:Tutorials:Collision Detection

From GPWiki

Files:GUITutorial_warn.gif The Game Programming Wiki has moved! Files:GUITutorial_warn.gif

The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server.

However, the GPWiki forums are still active! Come say hello.

Imagine: you're playing your brand-new, high-quality, processor-intensive video game. You're having a great time, killing bad guys, and all of a sudden, you step through the wall. Gravity and the physics engine kick in, and you just fall. Who knows how long you'll fall for, or why you're falling in the first place, but now you are out of the map. If you haven't experienced this before (collision detection = clipping in 3D games), that's good. The developers of whatever game you are playing have done well. Congrats to them.

This tutorial will help you to protect against instances described above.

If Object1.Top =< Object2.Top + Object2.Height And Object1.Top + Object1.Height => Object2.Top Then
  If Object1.Left =< Object2.Left + Object2.Width And Object1.Left + Object1.Width => Object2.Width Then
    'collision, Then statements go here
  End If
End if

Alright. The above code is basic collision detection for shapes, pictureboxes, textboxes, or any other control with Top, Height, Left, and Width properties. (Note: These can be combined into one If statement, but it's easier to manage and interpret this way)

These basic statements check the top and bottom of both objects, and then they check the left and right sides of the shapes. If your objects might collide from any possible side, then you should probably combine the two statements into one.

Detection Using Control Arrays

To implement control arrays for collision detection, the only change that is necessary is to initialize the array before checking, and to put the array into the statements as well.

For x = 0 to 9
 
If Object1.Top =< Object2(x).Top + Object2(x).Height And Object1.Top + Object1.Height => Object2(x).Top Then
  If Object1.Left =< Object2(x).Left + Object2(x).Width And Object1.Left + Object1.Width => Object2(x).Width Then
    'collision between the single projectile and one of the objects in the array, Then statements go here
  End If
End if

To use two control arrays is basically the same.