Monday, January 26, 2015

Implementing Explosion with Corona SDK


The gif is about 600K so please wait a bit..

While working on my physics-based game City of Carbon, I needed to implement an explosion that send physic objects flying.  This is what I came up with.    The code for explosion part is below.  If you use it, you will have to change the hardcoded values so it fits your game

Download the completed project at http://tmeta.com/files/ExplosionDemo.zip.





Explosion = {}

local sin = math.sin
local cos = math.cos
local random = math.random
local rad = math.rad

function Explosion:new(x, y)
    local expl = display.newGroup()
    local r = 80
    local angle = 0
    expl.x, expl.y = x, y
    local pdelay = 225/80 * r
    local balls = {}   
   
    function expl:exec()
        for a=0,360,30 do
            local ball = display.newRect(x, y, 10, 10)
            physics.addBody(ball, "dynamic", {density=1, bounce=0.5})
            ball.isBullet = true
            ball.linearDamping = 12 - ((r - 80) / 10)
            ball.gravityScale = 0
            ball.alpha = 1
            local ang = rad(a + angle)
            local f = 2500 / 80 * r
            ball:setLinearVelocity(f * sin(ang), f * cos(ang))
            table.insert(balls, ball)
            self:insert(ball)
           
            if a % 60 == 0 then
                local expl1 = display.newImage("smoke.png")
                self:insert(expl1)
                expl1.rotation = -a + 180
                local s0 = random(1, 10) / 100
                local s1 = random(100, 150/80*r) / 100
                expl1:scale(s0, s0)
                local ra = rad(random(a-20, a+20))
                local r2 = random(r-15, r+15)
                transition.to(expl1, {time=pdelay, x=r2*sin(ra), y=r2*cos(ra), xScale=s1, yScale=s1,
                    onComplete=function(o) o.alpha = 0 end})
            end
        end
        timer.performWithDelay(pdelay, function(e)
            balls = nil
            self:removeSelf()           
        end)
    end
   
    return expl
end
 

return Explosion

No comments:

Post a Comment