Hi folks, I’m trying to add lives to a game, but the math.max limiter prevents me from doing so. Anyone know how to remove math.max without harming the script?
code i’m using:
-- Define module local M = {} function M.new( options ) -- Default options for instance options = options or {} local image = options.image local max = options.max or 3 local spacing = options.spacing or 8 local w, h = options.width or 64, options.height or 64 -- Create display group to hold visuals local group = display.newGroup() local hearts = {} for i = 1, max do hearts[i] = display.newImageRect( "scene/game/img/shield.png", w, h ) hearts[i].x = (i-1) \* ( (w/2) + spacing ) hearts[i].y = 0 group:insert( hearts[i] ) end group.count = max function group:damage( amount ) group.count = math.min( max, math.max( 0, group.count - ( amount or 1 ) ) ) for i = 1, max do if i \<= group.count then hearts[i].alpha = 1 else hearts[i].alpha = 0.2 end end return group.count end function group:heal( amount ) self:damage( -( amount or 1 ) ) end function group:finalize() -- On remove, cleanup instance end group:addEventListener( "finalize" ) -- Return instance return group end return M
With this module, I show the lives:
shield = heartBar.new() shield.x = 48 shield.y = display.screenOriginY + shield.contentHeight / 2 + 16 hero.shield = shield
When hero collides with a life, I add it like this:
function instance:collision( event ) local phase, other = event.phase, event.other if phase == "began" and other.type == "hero" then other.shield:heal(1) end end
The game is inspired by the famous Sticker Knight Platformer master.
regards