tween
game/tween 使用 NSGo 的 core.Curve 緩動曲線,在 game.Loop 固定步長上確定性地驅動數值、座標、顏色、自定義型別、時間軸以及 tilemap.Camera 運鏡補間。
import "github.com/nsgo-dev/game/pkg/tween"
建立與推進 Tween
使用 Float32、Float64、Point、Color 或泛型 New[T] 建立 *Tween,可鏈式配置 Delay、Repeat 和 OnComplete,再通過 Update(dt) 或 Group 推進:
var group tween.Group
popup := tween.Float32(0, 1, 300*time.Millisecond, core.EaseOut, func(v float32) {
banner.ScaleX, banner.ScaleY = v, v
}).Delay(100 * time.Millisecond).
OnComplete(func() { bannerReady = true })
bob := tween.Float32(0, -6, 600*time.Millisecond, core.EaseInOut, func(y float32) {
coin.Y = baseY + y
}).Repeat(tween.RepeatForever, true) // 無限往返(yoyo)
group.Add(popup, bob)
// 在 game.Loop.Update 中:
group.Update(dt) // 完成的補間會自動移除
- 緩動曲線:零值
core.Curve預設為core.Linear。 Repeat(count, yoyo):在首輪之後額外重複count次(0表示只播一次;tween.RepeatForever或任意負數表示無限重複)。yoyo為true時,奇數輪反向從to插值回from。- 跳轉與重置:
tw.Seek(at)跳轉到指定時間點並立即應用該時刻的值(不觸發OnComplete);tw.Reset()倒回起點。可通過tw.Done()與tw.Duration()查詢狀態。 - 自定義型別:用
tween.New[T](from, to, d, curve, lerp, set)對任意結構體或向量做補間。
使用 Timeline 編排多軌動畫
Timeline 在同一條確定性時鐘上協調多段補間與定時回撥,支援播放、暫停、倒放、迴圈和精確拖拽(Seek):
tl := tween.NewTimeline().
Add(0, tween.Float32(0, 1, 400*time.Millisecond, core.EaseOut, setFade)).
Append(tween.Point(startPos, endPos, 800*time.Millisecond, core.EaseInOut, setPos)).
Call(600*time.Millisecond, func() { playSfx("whoosh") })
tl.Play()
// 在 game.Loop.Update 中:
tl.Update(dt)
Add(at, tw)將tw放到偏移量at處;Append(tw)將tw追加到時間軸當前的Duration()末尾。Call(at, fn)在播放跨越時間戳at時觸發fn(呼叫Seek時不觸發)。- 通過
Play()、Pause()、Restart()、Reverse(bool)、SetLoop(bool)和Seek(at)控制回放;Seek會把每條軌道(無論處於區間前、中、後)精確設到at時刻對應的狀態。
相機運鏡輔助函式
內建相機補間直接操作 *tilemap.Camera,並在設定了 cam.Bounds 時自動限位:
// 平移到 Boss 區域、拉近鏡頭,最後平滑切回跟隨玩家
intro := tween.NewTimeline().
Add(0, tween.CameraPan(cam, boss.X, boss.Y, 900*time.Millisecond, core.EaseInOut)).
Add(200*time.Millisecond, tween.CameraZoom(cam, 1.5, 700*time.Millisecond, core.EaseOut)).
Append(tween.CameraZoom(cam, 1.0, 500*time.Millisecond, core.EaseInOut)).
Append(tween.CameraFollowTransition(cam, func() core.Point {
return player.Pos
}, 600*time.Millisecond, core.EaseInOut))
intro.Play()
可用的相機補間建構函式:
| 輔助函式 | 動畫屬性 |
|---|---|
CameraPan(cam, toX, toY, d, curve) |
將 cam.X、cam.Y 從起始位置平移至 (toX, toY)。 |
CameraZoom(cam, toZoom, d, curve) |
將 cam.Zoom(<= 0 視為 1)縮放至 toZoom。 |
CameraRotate(cam, toRot, d, curve) |
將 cam.Rotation(弧度)旋轉至 toRot。 |
CameraMove(cam, toX, toY, toZoom, toRot, d, curve) |
同時驅動位置、縮放與旋轉。 |
CameraFollowTransition(cam, targetFn, d, curve) |
從相機起始位置平滑過渡到持續移動的 targetFn(),結束時精確落在該目標上。 |