Hello!
I have started making a game in which the player needs to be able to shoot. I know how to create the bullet mechanic in a single file however I want to structure my game using the composer API. I would like to have a ‘Bullet’ module that is responsible for creating the bullet instances however, I have a problem when I try to add an event listener to the bullet. When the bullet hits a sensor, I want the bullet to be removed however the only way I figured out was to create a global function which I know isn’t the best way to do it.
This is my code, I have left out any unnecessary code such as drawing other objects and the other functions such as ‘scene:create’ etc.
Note that I have wrote some comments in the code to make my question easier to understand.
game.lua
[lua]
local Bullet = require( ‘Bullet’ )
local bullet
local topSensor
topSensor.type = ‘topSensor’
– Creates a new instance of the bullet object with the players ‘x’ and ‘y’ position passed through
local function shoot( event )
if ( event.phase == ‘began’ ) then
bullet = Bullet.new( playerPosX, playerPosY )
end
end
– I have had to use a global function so that the event listener in ‘Bullet.lua’ can access the top sensor
function bulletCollision( event )
if ( event.phase == ‘began’ ) then
if ( event.other.type == ‘topSensor’ ) then
display.remove( event.target )
event.target = nil
end
end
end
function scene:show( event )
Runtime:addEventListener( ‘touch’, shoot )
end
[/lua]
Bullet.lua
[lua]
local function new( x, y )
local bullet = display.newRect( x, y, 10, 30 )
physics.addBody( bullet, ‘dynamic’ )
bullet.type = ‘bullet’
bullet.isSensor = true
bullet.gravityScale = 0
bullet:setLinearVelocity( 0, -1200 )
bullet:addEventListener( ‘collision’, bulletCollision ) – This is my issue, calling a global function.
return bullet
end
return {
new = new
}
[/lua]
My question is, is there a better way to do this without using a global function? This may be more of a Lua specific problem and not a Corona one so sorry if is posted in the wrong location.
Thanks.