Adding Bullets and Sound

Now we are going to add some bullets to the game when the user clicks the fire button. We will spawn the bullets to the right of the player sprite and allow a maximum of five bullets at a time. Of course, when each bullet is fired we will also illustrate how to play a sound effect.

type bullet
 	x# as float
 	y# as float
 	alive# as integer
 	spriteID# as integer
 	img# as integer


First, we create a structure or type to hold our bullet class. We also call createBullets() to setup the bullets, a function we are going to implement in just a few seconds, along with updateBullets() and fireBullets().

Let’s start with createBullet():

function createBullets()
	dim bullets[5] as bullet
	img_yellowbullet4 = LoadImage( "Missiles and Bullets/Double Size/yellow-bullet-4.png" )
	for i = 1 to 5
		bullets[i].x# = 0.0
		bullets[i].y# = 0.0
		bullets[i].alive# = 0
		bullets[i].spriteID# = 1000 + i
		bullets[i].img# = img_yellowbullet4
	next i

We create an array of 5 of our bullet type, then load a sprite by name instead of instancing it via drag and drop. When then simply flip through them setting default values, including a unique spriteID for each bullet.

Now that we have bullets to work with, let’s create the code to fire a bullet at the given x and y location.

function fireBullet(x,y)
   wav_laser1 = LoadSound( "Audio/laser1.wav" )
	//find first non-live bullet
   currentBullet = 0
   for i = 1 to 5
      if bullets[i].alive# = 0
      	currentBullet = i
   	next i
   	if currentBullet <> 0
   	   CreateSprite(bullets[currentBullet].spriteID#, bullets[currentBullet].img#)
   	   bullets[currentBullet].alive# = 1
   	   bullets[currentBullet].x# = x
   	   bullets[currentBullet].y# = y

Here we show how easy it is to play sound, first loading it using LoadSound() and recording the id, then playing that sound later by calling PlaySound and using that id. Otherwise, we loop through our array of bullets and find the first “not alive” bullet. If all 5 are active wee do nothing, otherwise, we create a sprite at the position specified, offset by the position of the player. Now finally the logic to manage the bullets in updateBullets():

function updateBullets()
	for i = 1 to 5
		if(bullets[i].alive# <> 0)
			bullets[i].x# = bullets[i].x# + 10
			SetSpritePosition(bullets[i].spriteID#,bullets[i].x#, bullets[i].y#)
			if(GetSpriteX(bullets[i].spriteID#) > GetScreenBoundsRight())
				bullets[i].alive# = 0
	next i	

We simply loop through the bullet array, if the bullet is alive we move it to the right. If the bullet goes off the right side of the screen we delete it and set it to “dead” in the array.

Finally, replace the Print(“BOOM”) code with a fireBullet() call. Then in the game loop add updateBullets().

Scroll to Top