最有效的文本缓动方式是什么

我想知道如何缓动文本,并且最有效的缓动方式是什么,我考虑使用Tween Service,但它只能缓动数字值,因此不可能对字符串进行缓动,我可以明显地按顺序添加每个字母,但是用这种方法制作段落需要花费一定时间,所以我需要一种有效且可行的方法来完成这个任务,以下是我尝试使用Tween Service的代码:

local serv = game:GetService("TweenService")
local start = script.Parent.TextLabel
local stop = {}
stop.Text = "hi there lol this is just a test"
local info = TweenInfo.new(5, Enum.EasingStyle.Sine)
local play = serv:Create(start, info, stop)
while true do
    wait(5)
    play:Play()
end

我知道这不起作用,但我还是尝试了一下。

点赞
用户2860267
用户2860267

正如你所发现的,你不能直接 tween 文本。Tween 是设计用来获取开始点和结束点并填补这两点之间的差距,但对于文本来说,不太清楚应该如何做到这一点。如果你的起点是“hello”,终点是“goodbye”,那么到达那里的步骤又是什么呢?

但如果你想要制作经典的打字机动画,你可以很容易地逐个字母地对文本进行动画处理。

这涉及循环整个文本消息并且每次取一些子字符串。这将使得每次动画更新时都会添加一个字母的外观。使用一些数学和 TweenService:GetValue,我们可以插值出动画的进度。

因此,请尝试以下内容:

local TweenService = game:GetService("TweenService")

local function writeText(targetLabel, text, duration, easingStyle, easingDirection)
    -- 校验输入
    local numLetters = #text
    if numLetters == 0 then
        targetLabel.Text = ""
        return
    end
    if easingStyle == nil then
        easingStyle = Enum.EasingStyle.Linear
    end
    if easingDirection == nil then
        easingDirection = Enum.EasingDirection.InOut
    end


    local startingTime = tick()
    local letterCount = 0
    while letterCount < numLetters do
        -- 计算动画进行的进度
        local timePassed = (tick() - startingTime)
        local percentDone = TweenService:GetValue(timePassed / duration, easingStyle, easingDirection)
        letterCount = math.ceil(percentDone * numLetters)
        local message = string.sub(text, 1, letterCount)

        -- 更新文本
        targetLabel.Text = message

        -- 等待以便动画播放
        wait(0.05)
    end
end

-- 测试
local lbl = script.Parent.TextLabel
local msg = "hi there lol this is just a test, it can be really long too."
local duration = 5 --seconds
local style = Enum.EasingStyle.Sine
local direction = Enum.EasingDirection.InOut
writeText(lbl, msg, duration, style, direction)
2021-03-01 21:02:14