Creating a Fire Button with Corona

A common feature of a mobile games is the ability to fire projectiles from the player. The projectiles could be bullets, lasers, fireballs, or every burgers! What ever you are firing, you’ll need a way for the player to fire these projectiles.

In this post, you’ll learn how to create a fire button that will fire a projectile when touched. Instead of using some cool graphics, I used Corona’s native objects to build this short post. The fire button is represented by a white rectangle and the bullets are represented by smaller white circles. I’ve pasted the code below, but essentially, when the fire button is touched, the touch event listener is triggered. Then, the function onTouch is called and a bullet is sent from the button to the top of screen. When the transition is complete, the bullet is removed to make sure we don’t run into any memory leaks. Here’s the full code:

local fireButton -- create a local forward

-- This function will shoot the bullet when the player touches the fire button. I wanted to use the began phase, but you can feel free to use the ended phase as well.
local function onTouch( self, event ) 
	if( event.phase == "began") then
		local bullet = display.newCircle(0,0,10)
		bullet.x = btn_fire.x
		bullet.y = btn_fire.y, {y=-100, onComplete=function(obj) display.remove(obj); end})   

-- Create a rectangle that represents are fire button
btn_fire = display.newRect( 100, 400, 50, 50 )
btn_fire.touch = onTouch -- assign .touch to function onTouch
btn_fire:addEventListener( "touch" ) -- add the event listener, without this, the game wouldn't run

And that’s it for adding a fire button to your game! There are plenty of things you can do to build on this. You could add collision detection, replace the objects with images, and make the bullet shoot from a player ship. If you have questions or comments, please leave them below!

Daniel Williams

Leave a Reply

Your email address will not be published. Required fields are marked *