Detecting Collisions

Click here to load the completed tutorial directly into the editor SWARM-21.DBA. If you want to step through and make the modifications, click here to load SWARM-20.DBA.

Now we have bullets flying in all directions, we need to detect when they hit something. We need to check three things. Whether a bullet hit an alien, whether a bullet hit the ship and whether an alien hit the ship.

Replace the line REM * HERE A * to read:
rem If player bullet visible
bulletobjid=bullet#(1,1)
if object visible(bulletobjid)=1

Replace the line REM * HERE C * to read:
rem Bullet visible endif
endif

Inside the _control_aliens subroutine, we check each alien to see whether they have been struck by the player bullet. It is important to only proceed with the check if the player bullet is visible.

Replace the line REM * HERE B * to read:
rem If alien and bullet collide, hide both objects
if object_distance(bulletobjid,objid)<10.0
hide object objid
hide object bulletobjid
endif

We are using a user defined function called object_distance() to calculate the actual distance between two objects. Keeping calculations like these within user defined functions makes the program cleaner, and reduces the overall size of your program by allowing you to re-use useful code. Our object_distance() function returns the distance between the alien and the bullet. If the distance is less than 10 then we hide both the alien and the bullet indicating that they have both been destroyed.

Replace the line REM * HERE D * to read:
rem If ship and alien collide, hide ship
shipobjid=50
if object_distance(shipobjid,objid)<10.0
hide object shipobjid
endif

Using the same object_distance() function, we check the distance between the ship and the alien object represented by the OBJID variable. If an alien is touching the ship, then the ship is destroyed.

Replace the line REM * HERE E * to read:
rem If ship and bullet collide, hide ship
shipobjid=50
if object_distance(shipobjid,objid)<10.0
hide object shipobjid
endif

In the _control_bullets subroutine, the ship is checked against each active bullet to detect for a possible collision with the alien bullets. If a bullet is close enough to the ship, the ship is destroyed.

Click Here For The Next Tutorial Adding The Level Loop.