TypeWriter @mokalux

From GiderosMobile

TypeWriter @mokalux Class

--[[ TextField TypeWriter Effect
-- based on the work of @pie & @koeosstudio, mixed by @mokalux ;-)
-- function TypeWriter:init(font, text, speed, char)
---- font: Font
---- text: string
---- speed: number (millisecond)
---- char: the number of characters to display at a time, default = 1
-- return event:
---- "finished"
---- data: speed
---- data: char
--
--- warnings:
--- almost work with "\e[color=#f005]text\e[color]" Gideros tag
]]

TypeWriter = Core.class(TextField)

function TypeWriter:init(font, text, speed, char)
	self:setVisible(false) -- start invisible
	local i = 0
	local in_str = text
	local str_length = in_str:len()
	local typeSpeedTimer = Timer.new(speed or 100, str_length)
	char = char or 1

	local function getString()
		if i <= str_length then
			i += char -- number of characters to add each time
			local out_str = in_str:sub(1, i)
			self:setText(out_str)
			self:setVisible(true)
		else
			local ev = Event.new("finished")
			ev.speed = speed
			ev.char = char
			self:dispatchEvent(ev)
		end
	end
	typeSpeedTimer:addEventListener(Event.TIMER, getString)
	typeSpeedTimer:start()
	self:setFont(font)
end

TypeWriter @mokalux Demo

-- DEMO
application:setBackgroundColor(0x6c6c6c)

local fnt = TTFont.new("fonts/Kenney Blocks.ttf", 14)
local fnt2 = TTFont.new("fonts/Kenney Blocks.ttf", 20)

local test = [[
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
]]
local test2 = "Viva \e[color=#f00]Gideros\e[color]!" -- almost working!
--local test2 = "Viva Gideros!"

local tw = TypeWriter.new(fnt, test, 100*1, 4)
tw:setLayout( { w=480, flags=FontBase.TLF_CENTER } ) -- WORKING!

tw:addEventListener("finished", function(e)
	local tw2 = TypeWriter.new(fnt2, test2, e.speed*3, e.char/2)
	tw2:setLayout( { w=480, flags=FontBase.TLF_CENTER } ) -- NOT WORKING!?
	tw2:setTextColor(0xffff00)
	tw2:setPosition(64, 64*3.5)
	stage:addChild(tw2)
end)

-- position
tw:setPosition(64, 64)
-- order
stage:addChild(tw)


UI Text