Page 1 of 1

animation and flow timers

Posted: Thu Jun 02, 2011 9:10 pm
by sentry
Hi, I'm just starting out with love2d and i have a question about timers.

In a regular shoot em up the player flickers and is invincible for a couple of seconds after losing a life.
It was easy to implement this feature but i wonder if there is a better/smarter way to do this.

This is what i do in the update routine of the player object:

Code: Select all

if invincible then
	invincible_indicator_timer = invincible_indicator_timer + 1 * dt
	if invincible_indicator_timer <= 2 then
		invincible_timer = invincible_timer + 1 * dt
		if invincible_timer >= 0.05 then
			active_image = 'invincible'
			invincible_timer = 0
		else
			active_image = 'normal'
		end
	else
		active_image = 'normal'
		invincible = false
		invincible_indicator_timer = 0
	end
end
When the player loses a life; i set invincible to true. Then i switch between 2 images for for two seconds to mimick the flickering effect.
In the collision detection routine i check for player.invincible to ignore collisions.

Is this how i should do stuff like this or are there better ways?

Regards, TM

Re: animation and flow timers

Posted: Fri Jun 03, 2011 12:57 am
by Taehl
You could probably shorten it with some fancy short-circuit evaluation and modulo math or something, but really, that looks fine to me. Just because there's always a better solution doesn't mean you should get stuck trying to find it for every little thing. Good luck on your game.

Re: animation and flow timers

Posted: Fri Jun 03, 2011 10:55 am
by sentry
Ok thanks. I should be more focused at actually completing the game. It's just that this example is not the only timer- i have loads of them to control the flow of the game.

Re: animation and flow timers

Posted: Fri Jun 03, 2011 11:05 am
by vrld
Taehl wrote:Just because there's always a better solution doesn't mean you should get stuck trying to find it for every little thing.
This!

But because I'm biased, I'll point you to hump.timer.
Using it, you can write code like that:

Code: Select all

function player:setInvincible(duration)
    local duration = duration or 2
    self.invincible = true
    Timer.add(duration, function()
        self.invincible = false
        self.active_image = 'normal' -- reset image
    end)
    
    local flicker_times = math.floor(duration / 0.05)
    Timer.addPeriodic(0.05, function()
        if not self.invincible then return end -- don't switch image if still invincible
        self.active_image = self.active_image == 'normal' and 'invincible' or 'normal' -- flip image
    end, flicker_times)
end

Re: animation and flow timers

Posted: Fri Jun 03, 2011 10:18 pm
by sentry
This is what i was looking for, a nice generic solution for timers. Thank you.

Re: animation and flow timers

Posted: Sat Jun 04, 2011 12:41 pm
by kikito
There's also cron.lua if you are into timers