• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# Basic Collision Dection

## Recommended Posts

I am currently working on a simple game for a final project in my programming class, and I need to figure out a way to detect a collision between a bullet and a target. The game is similar to scorched earth in concept. Right now I''ve set up the dection as follows: For TarY = 0 To 240 For BulY = 0 To 135 If TrgtY(TarY) = BulletY(BulY) Then For TarX = 0 To 240 For BulX = 0 To 135 If TrgtX(TarX) = BulletX(BulX) Then Shot = True Explosion ResetBullet MsgBox "Great Shot!" Amt = frmAnimation.imgTarget.Count - 1 Unload frmAnimation.imgTarget(Amt) Score = Score + 50 Shots = Shots + 3 StatusUp CreateTarget Exit Sub End If Next BulX Next TarX End If Next BulY Next TarY All of this works, however it taxes the CPU''s at school way too much as it runs this sub each time the screen refreshes. What I''ve done is load each image into an array, so that each pixel(twip) is loaded as an x,y coordinate. (Game is 2d and written in Visual Basic) So is there a way to increase the efficiency of the dection while achieving the same results? TIA... ''Gain

##### Share on other sites
Gaiiden    5710
if the target is an unmoving object, the simplest way is to create a bounding box. For example, you would need to make a Rectangle type:
Type Rectangle    x as integer    y as integer    w as integer    h as integerEnd Type

Using the above type, you can assign a bounding box to the target area. Note that x and y are the top-left coordinates of the box. w and h supply the width and height.

The simplest test is to take the x,y position of the bullet and determine if the position is within the x boundary (x to x+w) and the y boundary (y to y+h):
if ((bullet_x < (target.x + target.w)) And (bullet_x > target.x)) Then    if ((bullet_y < (target.y + target.h)) And (bullet_y > target.y)) Then	' hit

If the bullet is large relative to the target, you may want to create a bounding box for the bullet so that, for instance, it doesn't seem to pass halfway through the target before registering a hit. In this case you would test the border in the direction the bullet is traveling (it makes no sense to check the other three, only the one in front will hit first).

Oh and if the target is moving, don't forget that you have to update the x and y values for the bounding box as well (but no need to touch the w and h). a simple offset constant from the main x,y will do.

_________________________________________________________________

Drew Sikora
A.K.A. Gaiiden

ICQ #: 70449988
AOLIM: DarkPylat