cocos2d x實現打字特效

2021-09-19 23:16:17 字數 2943 閱讀 7200

原文請猛戳:

這次分享乙個在cocos2d-x中實現打字特效的小功能。

首先,cocos2d-x中label預設是utf8編碼,quickx提供了乙個string.utf8len介面,這裡再加乙個擷取子字串的函式:

function utf8str(str, start, num)

local function utf8charsize(char)

if not char then

return 0

elseif char > 240 then

return 4

elseif char > 225 then

return 3

elseif char > 192 then

return 2

else

return 1

endend

local startidx = 1

while start > 1 do

local char = string.byte(str, startidx)

startidx = startidx + utf8charsize(char)

start = start - 1

endlocal endidx = startidx

while num > 0 do

if endidx > #str then

endidx = #str

break

endlocal char = string.byte(str, idx)

endidx = endidx + utf8charsize(char)

num = num - 1

endreturn str:sub(startidx, endidx - 1)

end

第一種實現方式是一開始把每個字元scale到0,延遲一定時間後再scale到原大小:

-- textdelaytime為每個字顯示的延遲時間

function typewriting(label, textdelaytime)

string = label:getstring()

-- 這裡考慮了label可能有換行的情況

local totallen = string.utf8len(string) + label:getstringnumlines()

for i = 1, totallen do

local sprite = label:getletter(i - 1)

if sprite then

sprite:setscale(0)

endend

for i = 1, totallen do

local textdelay = cc.delaytime:create(textdelaytime * (i - 1))

local sprite = label:getletter(i - 1)

if sprite then

sprite:runaction(textactionseq)

endend

end

這種實現的效果有跳入感,換一種方式,用visibility來控制:

-- textdelaytime為每個字顯示的延遲時間

function typewriting(label, textdelaytime)

string = label:getstring()

-- 這裡考慮了label可能有換行的情況

local totallen = string.utf8len(string) + label:getstringnumlines()

for i = 1, totallen do

local sprite = label:getletter(i - 1)

if sprite then

sprite:setvisible(false)

endend

for i = 1, totallen do

local textdelay = cc.delaytime:create(textdelaytime * (i - 1))

local sprite = label:getletter(i - 1)

if sprite then

sprite:runaction(textactionseq)

endend

end

這種效果也沒好多少,最後本渣換了一種思路,不按乙個字乙個字來runaction了,改為把label作為整體來runaction,在action中去setstring,這種方式的效果好多了:

-- textdelaytime為每個字顯示的延遲時間

function typewriting(label, textdelaytime)

string = label:getstring()

-- 這裡考慮了label可能有換行的情況

local totallen = string.utf8len(string) + label:getstringnumlines()

label:setstring("")

local textactions = {}

for i = 1, totallen do

local textdelay = cc.delaytime:create(textdelaytime)

label:setstring(utf8str(string, 1, i))

end)

table.insert(textactions, textdelay)

endlocal textactionseq = cc.sequence:create(textactions)

label:runaction(textactionseq)

end

cocos2d x 自帶11種粒子特效

粒子效果,存下來以備後用,實現方法很簡單,自己找張粒子,然後將 拷貝到helloworld的init函式裡,就可以實現 粒子特效 效果 ccparticlesystem particlesystem ccparticleexplosion create particlesystem settextu...

cocos2d x 實現中文輸出

下面我們來說說如何實現中文輸出吧!首先,個人覺得可以新建乙個tools.cpp 和 tools.h 檔案 首先在tools.h ifndef tools h 預定義塊 define tools h include cocos2d.h if cc target platform cc platform...

cocos2d x實現中文顯示 筆記

cocos2d x在win32開發中,不能直接顯示中文,需要轉字元。cocos2d x已經自帶了乙個對應的庫iconv。如果要使用它,我們要在做以下配置 1.右鍵專案 屬性 附加包含目錄 編輯。然後新增乙個路徑,我的如下 d cocos2d x cocos2d 2.0 x 2.0.4 cocos2d...