Page 1 of 1

Animate images by varying opacity

Posted: Tue Oct 17, 2017 10:46 pm
by Spacebrain
Hello!

I've been trying to animate some images in a particular way by overlapping them and varying each image's opacity but with no success.
I've looked for a library or a code snippet that could do that but with no luck...
I have no problem controlling each image's opacity, I just can't figure out how I should implement the "varying opacity" part I want.

Let's say that I want to animate 4 images:
  • All images are drawn with an opacity of 0
  • Image1's opacity tweens to 128
  • At the moment Image1's opacity reachs 128, Image2's opacity tweens to 128
  • At the moment Image2's opacity reachs 128, Image1's opacity tweens to 0 and Image3's opacity tweens to 128
  • At the moment Image3's opacity reachs 128, Image2's opacity tweens to 0 and Image4's opacity tweens to 128
  • At the moment Image4's opacity reachs 128, Image3's opacity tweens to 0 and Image1's opacity tweens to 128
  • And so on...
I use timer.tween from HUMP for tweening.

If any of you have every done something similar before or have an idea of how to do that, I'm all ears!
Thanks :nyu:

Re: Animate images by varying opacity

Posted: Wed Oct 18, 2017 12:54 am
by grump
I don't use HUMP, but it probably provides a way to set a callback that gets called when a tween ends. Use that to make a chain by starting the next tween when the previous one ends.

Re: Animate images by varying opacity

Posted: Wed Oct 18, 2017 1:02 am
by Azhukar

Code: Select all

Timer = require "hump.timer"

local function nextImage()
	return {
		color = {math.random()*255,math.random()*255,math.random()*255},
		alpha = 0,
		x = math.random()*100+100,
		y = math.random()*100+100,
	}
end

local lastImage,currentImage
local function afterTween()
	lastImage = currentImage
	currentImage = nextImage() --yours to define
	Timer.tween(1,lastImage,{alpha=0},"linear",afterTween)
	Timer.tween(1,currentImage,{alpha=128},"linear")
end

function love.load()
	love.graphics.setBackgroundColor(128,128,128)
	currentImage = nextImage()
	Timer.tween(1,currentImage,{alpha=128},"linear",afterTween)
end

function love.update(dt)
    Timer.update(dt)
end

function love.draw()
	if (lastImage ~= nil) then
		local c = lastImage.color
		love.graphics.setColor(c[1],c[2],c[3],lastImage.alpha)
		love.graphics.rectangle("fill",lastImage.x,lastImage.y,100,100)
	end
	local c = currentImage.color
	love.graphics.setColor(c[1],c[2],c[3],currentImage.alpha)
	love.graphics.rectangle("fill",currentImage.x,currentImage.y,100,100)
end