tween

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 6 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tween animates values, timelines, and tilemap cameras deterministically on fixed game.Loop steps using NSGo easing curves.

Index

Examples

Constants

View Source
const RepeatForever = -1

RepeatForever repeats a tween indefinitely when passed to Tween.Repeat.

Variables

View Source
var (
	SineIn    = makeEase(func(t float64) float64 { return 1 - math.Cos(t*math.Pi/2) })
	SineOut   = easeOutOf(SineIn)
	SineInOut = easeInOutOf(SineIn)
	SineOutIn = easeOutInOf(SineIn, SineOut)

	QuadIn    = makeEase(func(t float64) float64 { return t * t })
	QuadOut   = easeOutOf(QuadIn)
	QuadInOut = easeInOutOf(QuadIn)
	QuadOutIn = easeOutInOf(QuadIn, QuadOut)

	CubicIn    = makeEase(func(t float64) float64 { return t * t * t })
	CubicOut   = easeOutOf(CubicIn)
	CubicInOut = easeInOutOf(CubicIn)
	CubicOutIn = easeOutInOf(CubicIn, CubicOut)

	QuartIn    = makeEase(func(t float64) float64 { return t * t * t * t })
	QuartOut   = easeOutOf(QuartIn)
	QuartInOut = easeInOutOf(QuartIn)
	QuartOutIn = easeOutInOf(QuartIn, QuartOut)

	QuintIn    = makeEase(func(t float64) float64 { return t * t * t * t * t })
	QuintOut   = easeOutOf(QuintIn)
	QuintInOut = easeInOutOf(QuintIn)
	QuintOutIn = easeOutInOf(QuintIn, QuintOut)

	ExpoIn = makeEase(func(t float64) float64 {
		if t <= 0 {
			return 0
		}
		return math.Pow(2, 10*(t-1))
	})
	ExpoOut = makeEase(func(t float64) float64 {
		if t >= 1 {
			return 1
		}
		return 1 - math.Pow(2, -10*t)
	})
	ExpoInOut = easeInOutFromPair(ExpoIn, ExpoOut)
	ExpoOutIn = easeOutInOf(ExpoIn, ExpoOut)

	CircIn = makeEase(func(t float64) float64 {
		return 1 - math.Sqrt(math.Max(0, 1-t*t))
	})
	CircOut = makeEase(func(t float64) float64 {
		u := t - 1
		return math.Sqrt(math.Max(0, 1-u*u))
	})
	CircInOut = easeInOutFromPair(CircIn, CircOut)
	CircOutIn = easeOutInOf(CircIn, CircOut)

	BackIn = makeEase(func(t float64) float64 {
		return t * t * ((backS+1)*t - backS)
	})
	BackOut = makeEase(func(t float64) float64 {
		u := t - 1
		return 1 + u*u*((backS+1)*u+backS)
	})
	BackInOut = makeEase(func(t float64) float64 {
		const c2 = backS * 1.525
		if t < 0.5 {
			x := 2 * t
			return 0.5 * x * x * ((c2+1)*x - c2)
		}
		x := 2*t - 2
		return 0.5*x*x*((c2+1)*x+c2) + 1
	})
	BackOutIn = easeOutInOf(BackIn, BackOut)

	ElasticIn = makeEase(func(t float64) float64 {
		if t <= 0 || t >= 1 {
			return t
		}
		return -math.Pow(2, 10*(t-1)) * math.Sin((10*t-10.75)*elasticC4)
	})
	ElasticOut = makeEase(func(t float64) float64 {
		if t <= 0 || t >= 1 {
			return t
		}
		return math.Pow(2, -10*t)*math.Sin((10*t-0.75)*elasticC4) + 1
	})
	ElasticInOut = easeInOutFromPair(ElasticIn, ElasticOut)
	ElasticOutIn = easeOutInOf(ElasticIn, ElasticOut)

	BounceOut = makeEase(func(t float64) float64 {
		const n1 = 7.5625
		const d1 = 2.75
		switch {
		case t < 1/d1:
			return n1 * t * t
		case t < 2/d1:
			t -= 1.5 / d1
			return n1*t*t + 0.75
		case t < 2.5/d1:
			t -= 2.25 / d1
			return n1*t*t + 0.9375
		default:
			t -= 2.625 / d1
			return n1*t*t + 0.984375
		}
	})
	BounceIn = makeEase(func(t float64) float64 {
		return 1 - float64(BounceOut(f32(1-t)))
	})
	BounceInOut = easeInOutFromPair(BounceIn, BounceOut)
	BounceOutIn = easeOutInOf(BounceIn, BounceOut)

	// SpringOut overshoots with a damped oscillation that settles exactly on 1;
	// the other spring variants mirror and combine the same wave.
	SpringOut = makeEase(func(t float64) float64 {
		if t <= 0 {
			return 0
		}
		if t >= 1 {
			return 1
		}
		return 1 - (1-t)*math.Exp(-3*t)*math.Cos(6*math.Pi*t)
	})
	SpringIn    = easeOutOf(SpringOut)
	SpringInOut = easeInOutFromPair(SpringIn, SpringOut)
	SpringOutIn = easeOutInOf(SpringIn, SpringOut)
)

Named easing functions covering the sine, quad, cubic, quart, quint, expo, circ, back, elastic, bounce and spring families, each in the in, out, in-out and out-in variants. All of them are exact at the endpoints: f(0) == 0 and f(1) == 1.

Functions

This section is empty.

Types

type CatmullRomCurve

type CatmullRomCurve struct {
	// contains filtered or unexported fields
}

CatmullRomCurve is a C1-continuous Catmull-Rom spline passing through all control points.

func CatmullRom

func CatmullRom(points []core.Point, closed bool, alpha float32) *CatmullRomCurve

CatmullRom returns a Catmull-Rom spline through points with parameterization exponent alpha (0 = uniform, 0.5 = centripetal, 1 = chordal). Negative alpha is clamped to 0.

func CatmullRomFromTiledObject

func CatmullRomFromTiledObject(obj tilemap.Object) *CatmullRomCurve

CatmullRomFromTiledObject converts a Tiled polyline (open) or polygon (closed) object translated by (obj.X, obj.Y) into a centripetal CatmullRomCurve.

func NewCatmullRom

func NewCatmullRom(points []core.Point, closed bool) *CatmullRomCurve

NewCatmullRom returns a centripetal Catmull-Rom spline (alpha = 0.5) passing through points.

func (*CatmullRomCurve) Closed

func (c *CatmullRomCurve) Closed() bool

Closed reports whether the Catmull-Rom spline forms a closed loop.

func (*CatmullRomCurve) Length

func (c *CatmullRomCurve) Length() float32

Length returns the total arc length of the Catmull-Rom spline.

func (*CatmullRomCurve) Point

func (c *CatmullRomCurve) Point(t float32) core.Point

Point evaluates the Catmull-Rom spline at parameter t in [0, 1].

func (*CatmullRomCurve) PointAtDistance

func (c *CatmullRomCurve) PointAtDistance(dist float32) core.Point

PointAtDistance returns the point at arc-length distance dist along the spline.

func (*CatmullRomCurve) Tangent

func (c *CatmullRomCurve) Tangent(t float32) core.Point

Tangent returns the unit-length tangent vector at parameter t in [0, 1].

func (*CatmullRomCurve) TangentAtDistance

func (c *CatmullRomCurve) TangentAtDistance(dist float32) core.Point

TangentAtDistance returns the unit-length tangent vector at arc-length distance dist along the spline.

type CubicBezierCurve

type CubicBezierCurve struct {
	// contains filtered or unexported fields
}

CubicBezierCurve is a cubic Bézier curve defined by four control points.

func CubicBezier

func CubicBezier(p0, p1, p2, p3 core.Point) *CubicBezierCurve

CubicBezier returns a cubic Bézier curve from p0 to p3 with control points p1 and p2.

func (*CubicBezierCurve) Closed

func (c *CubicBezierCurve) Closed() bool

Closed reports false because a cubic Bézier curve is open.

func (*CubicBezierCurve) Length

func (c *CubicBezierCurve) Length() float32

Length returns the total arc length of the cubic Bézier curve.

func (*CubicBezierCurve) Point

func (c *CubicBezierCurve) Point(t float32) core.Point

Point evaluates the cubic Bézier curve at parameter t in [0, 1].

func (*CubicBezierCurve) PointAtDistance

func (c *CubicBezierCurve) PointAtDistance(dist float32) core.Point

PointAtDistance returns the point at arc-length distance dist along the curve.

func (*CubicBezierCurve) Tangent

func (c *CubicBezierCurve) Tangent(t float32) core.Point

Tangent returns the unit-length tangent vector at parameter t in [0, 1].

func (*CubicBezierCurve) TangentAtDistance

func (c *CubicBezierCurve) TangentAtDistance(dist float32) core.Point

TangentAtDistance returns the unit-length tangent vector at arc-length distance dist along the curve.

type Curve

type Curve interface {
	// Point evaluates the curve at parameter t in [0, 1] (clamped).
	Point(t float32) core.Point
	// Tangent returns the unit-length tangent vector at parameter t in [0, 1] (clamped),
	// or the zero point if the curve is degenerate (zero length).
	Tangent(t float32) core.Point
	// Length returns the total arc length of the curve.
	Length() float32
	// PointAtDistance returns the point at arc-length distance dist along the curve (clamped to [0, Length()]).
	PointAtDistance(dist float32) core.Point
	// TangentAtDistance returns the unit-length tangent vector at arc-length distance dist along the curve (clamped to [0, Length()]).
	TangentAtDistance(dist float32) core.Point
	// Closed reports whether the curve forms a closed loop.
	Closed() bool
}

Curve is a 2D parametric curve with arc-length parameterization.

func CurveFromTiledObject

func CurveFromTiledObject(obj tilemap.Object, smooth bool) Curve

CurveFromTiledObject converts a Tiled polyline (open) or polygon (closed) object translated by (obj.X, obj.Y) into a Curve: a centripetal Catmull-Rom spline when smooth is true, or a Polyline otherwise.

type Ease

type Ease = EaseFunc

Ease maps normalized pass progress t in [0, 1] to an eased progress value, the same function type as EaseFunc. Named eases share the names of the interp values that resource curve keys use, so the same set is available from code and from clips.

type EaseFunc

type EaseFunc func(t float32) float32

EaseFunc maps normalized pass progress t in [0, 1] to an eased progress value.

func EaseFromCurve

func EaseFromCurve(c core.Curve) EaseFunc

EaseFromCurve adapts an NSGo core.Curve easing curve into an EaseFunc.

type FollowerOptions

type FollowerOptions struct {
	// Speed is the constant travel speed in points per second along the curve's arc length.
	// Used when Duration <= 0.
	Speed float32
	// Duration is the total travel time for one pass along the curve.
	// When Duration > 0, it takes precedence over Speed.
	Duration time.Duration
	// Ease maps normalized pass progress [0, 1] to eased arc-length fraction.
	// When nil and Curve is zero, motion proceeds linearly by arc length.
	Ease EaseFunc
	// Curve is an optional NSGo easing curve used when Ease is nil.
	Curve core.Curve
	// Loop controls playback behavior on reaching the end of the curve.
	Loop LoopMode
	// OrientToTangent computes Angle() from the curve tangent (atan2(ty, tx)) plus RotationOffset.
	// When false, Angle() returns RotationOffset.
	OrientToTangent bool
	// RotationOffset is added in radians to the heading angle.
	RotationOffset float32
	// OnUpdate is invoked whenever the follower moves or seeks with the current position and angle (radians).
	OnUpdate func(pos core.Point, angle float32)
	// OnComplete is invoked once when a LoopNone follower finishes the curve.
	OnComplete func()
}

FollowerOptions configures a PathFollower.

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group steps a collection of active tweens and timelines together and removes each once it finishes. Its zero value is ready to use.

Example

A Group updates many independent tweens together and drops them as they finish.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/tween"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	var g tween.Group
	g.Add(
		tween.Float64(0, 1, 100*time.Millisecond, core.Linear, func(float64) {}),
		tween.Float64(0, 1, 300*time.Millisecond, core.Linear, func(float64) {}),
	)
	g.Update(200 * time.Millisecond)
	fmt.Println(g.Len())
}
Output:
1

func (*Group) Add

func (g *Group) Add(tweens ...*Tween)

Add registers one or more non-nil tweens to be stepped by Update.

func (*Group) AddTimeline

func (g *Group) AddTimeline(tls ...*Timeline)

AddTimeline registers one or more non-nil timelines to be stepped by Update.

func (*Group) Bind

func (g *Group) Bind(cx *core.Scope)

Bind clears the group when the scope ends, using the scope's cleanup.

func (*Group) Clear

func (g *Group) Clear()

Clear removes all tweens and timelines from the group.

func (*Group) Len

func (g *Group) Len() int

Len returns the number of active tweens currently in the group.

func (*Group) Paused

func (g *Group) Paused() bool

Paused reports whether the group is suspended.

func (*Group) Remove

func (g *Group) Remove(tw *Tween)

Remove deletes tw from the group if present.

func (*Group) SetPaused

func (g *Group) SetPaused(paused bool)

SetPaused suspends the whole group without stopping any tween or timeline, so a game can freeze tweens while its pause menu is up.

func (*Group) SetSpeed

func (g *Group) SetSpeed(s float64)

SetSpeed scales every step by s, so the whole group runs in slow motion (0.25) or fast forward. A scale of 0 stops advancement; negative values and NaN are treated as 1.

func (*Group) Update

func (g *Group) Update(dt time.Duration)

Update advances every active tween and timeline in the group by dt and removes any that finish.

type LoopMode

type LoopMode int

LoopMode controls what a PathFollower does on reaching the end of a curve.

const (
	// LoopNone stops at the end of the curve and fires OnComplete once.
	LoopNone LoopMode = iota
	// LoopRepeat wraps back to the beginning of the curve and continues indefinitely.
	LoopRepeat
	// LoopPingPong reverses direction at each end of the curve and oscillates indefinitely.
	LoopPingPong
)

type PathFollower

type PathFollower struct {
	// contains filtered or unexported fields
}

PathFollower advances deterministically along a Curve by arc length, maintaining constant speed or easing cleanly over a fixed Duration.

Example

A PathFollower moves along a curve at a constant speed, for platforms or enemies on a route.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/tween"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	route := tween.Polyline([]core.Point{{X: 0, Y: 0}, {X: 100, Y: 0}, {X: 100, Y: 50}}, false)
	f := tween.NewPathFollower(route, tween.FollowerOptions{Speed: 50})
	for range 3 {
		f.Update(time.Second)
		fmt.Println(f.Position(), f.Distance())
	}
	fmt.Println(f.Done())
}
Output:
{50 0} 50
{100 0} 100
{100 50} 150
true

func NewPathFollower

func NewPathFollower(curve Curve, opts FollowerOptions) *PathFollower

NewPathFollower returns a PathFollower positioned at the start of curve.

func (*PathFollower) Angle

func (f *PathFollower) Angle() float32

Angle returns the follower's current heading angle in radians.

func (*PathFollower) Distance

func (f *PathFollower) Distance() float32

Distance returns the follower's current arc-length distance from the start of the curve.

func (*PathFollower) Done

func (f *PathFollower) Done() bool

Done reports whether a non-looping follower has reached the end of the curve.

func (*PathFollower) Position

func (f *PathFollower) Position() core.Point

Position returns the follower's current position along the curve.

func (*PathFollower) Progress

func (f *PathFollower) Progress() float32

Progress returns the follower's normalized progress in [0, 1] along the curve.

func (*PathFollower) Reset

func (f *PathFollower) Reset()

Reset rewinds the follower back to the start of the curve so it can run again.

func (*PathFollower) Seek

func (f *PathFollower) Seek(progress float32)

Seek moves the follower directly to normalized progress in [0, 1] without firing OnComplete.

func (*PathFollower) Step

func (f *PathFollower) Step(dt float32)

Step advances the follower by dt seconds.

func (*PathFollower) Tangent

func (f *PathFollower) Tangent() core.Point

Tangent returns the follower's current unit-length tangent vector.

func (*PathFollower) Tween

func (f *PathFollower) Tween() *Tween

Tween returns a *Tween backed by this follower so it integrates directly with Group and Timeline. It uses the follower's Duration (or Length/Speed when Duration <= 0), Loop mode, easing, and callbacks.

func (*PathFollower) Update

func (f *PathFollower) Update(dt time.Duration)

Update advances the follower by dt.

type PolylineCurve

type PolylineCurve struct {
	// contains filtered or unexported fields
}

PolylineCurve is a piecewise-linear curve through a sequence of vertices with exact arc-length lookup.

func Polyline

func Polyline(points []core.Point, closed bool) *PolylineCurve

Polyline returns a piecewise-linear curve through points. When closed is true and the last point differs from the first, an explicit closing segment back to points[0] is added.

func PolylineFromTiledObject

func PolylineFromTiledObject(obj tilemap.Object) *PolylineCurve

PolylineFromTiledObject converts a Tiled polyline (open) or polygon (closed) object translated by (obj.X, obj.Y) into a PolylineCurve.

func (*PolylineCurve) Closed

func (c *PolylineCurve) Closed() bool

Closed reports whether the polyline forms a closed loop.

func (*PolylineCurve) Length

func (c *PolylineCurve) Length() float32

Length returns the exact total length of the polyline.

func (*PolylineCurve) Point

func (c *PolylineCurve) Point(t float32) core.Point

Point evaluates the polyline at arc-length fraction t in [0, 1].

func (*PolylineCurve) PointAtDistance

func (c *PolylineCurve) PointAtDistance(dist float32) core.Point

PointAtDistance returns the exact point at arc-length distance dist along the polyline.

func (*PolylineCurve) Tangent

func (c *PolylineCurve) Tangent(t float32) core.Point

Tangent returns the unit-length tangent vector at arc-length fraction t in [0, 1].

func (*PolylineCurve) TangentAtDistance

func (c *PolylineCurve) TangentAtDistance(dist float32) core.Point

TangentAtDistance returns the unit-length tangent vector at arc-length distance dist along the polyline.

type QuadraticBezierCurve

type QuadraticBezierCurve struct {
	// contains filtered or unexported fields
}

QuadraticBezierCurve is a quadratic Bézier curve defined by three control points.

func QuadraticBezier

func QuadraticBezier(p0, p1, p2 core.Point) *QuadraticBezierCurve

QuadraticBezier returns a quadratic Bézier curve from p0 to p2 controlled by p1.

func (*QuadraticBezierCurve) Closed

func (c *QuadraticBezierCurve) Closed() bool

Closed reports false because a quadratic Bézier curve is open.

func (*QuadraticBezierCurve) Length

func (c *QuadraticBezierCurve) Length() float32

Length returns the total arc length of the quadratic Bézier curve.

func (*QuadraticBezierCurve) Point

func (c *QuadraticBezierCurve) Point(t float32) core.Point

Point evaluates the quadratic Bézier curve at parameter t in [0, 1].

func (*QuadraticBezierCurve) PointAtDistance

func (c *QuadraticBezierCurve) PointAtDistance(dist float32) core.Point

PointAtDistance returns the point at arc-length distance dist along the curve.

func (*QuadraticBezierCurve) Tangent

func (c *QuadraticBezierCurve) Tangent(t float32) core.Point

Tangent returns the unit-length tangent vector at parameter t in [0, 1].

func (*QuadraticBezierCurve) TangentAtDistance

func (c *QuadraticBezierCurve) TangentAtDistance(dist float32) core.Point

TangentAtDistance returns the unit-length tangent vector at arc-length distance dist along the curve.

type SequenceBuilder

type SequenceBuilder struct {
	// contains filtered or unexported fields
}

SequenceBuilder chains tween steps onto a Timeline without computing start times by hand: Then appends a step after the previous block, With runs a step in parallel with the last one, Wait inserts an interval and Call schedules a callback at the cursor.

func Sequence

func Sequence() *SequenceBuilder

Sequence returns an empty SequenceBuilder ready to chain steps.

Example

A Sequence chains steps without computing start times by hand: Then appends, With runs in parallel with the last step, Wait inserts an interval, and Loops repeats the run.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/tween"
)

func main() {
	var scale, y float32
	seq := tween.Sequence().
		Then(tween.To(&scale, 1.4, 80*time.Millisecond, tween.BackOut)).
		With(tween.By(&y, -40, 300*time.Millisecond, tween.QuadOut, nil, nil)).
		Wait(100 * time.Millisecond).
		Then(tween.To(&scale, 0.5, 200*time.Millisecond, tween.ElasticOut)).
		Build()
	fmt.Println(seq.Duration())
	seq.Play()
	seq.Update(300 * time.Millisecond)
	fmt.Println(scale, y)
	seq.Update(300 * time.Millisecond)
	fmt.Println(scale, seq.Done())
}
Output:
600ms
1.4 -40
0.5 true

func (*SequenceBuilder) Build

func (b *SequenceBuilder) Build() *Timeline

Build returns the timeline the builder assembled. Build may be called once; keep using the returned timeline and do not add steps to the builder afterwards.

func (*SequenceBuilder) Call

func (b *SequenceBuilder) Call(fn func()) *SequenceBuilder

Call schedules fn to run when playback reaches the cursor.

func (*SequenceBuilder) Loops

func (b *SequenceBuilder) Loops(n int) *SequenceBuilder

Loops sets how many runs the built timeline plays: n <= 0 wraps forever, n == 1 plays once and larger n wraps n-1 more times, like Timeline.SetLoops.

func (*SequenceBuilder) Then

func (b *SequenceBuilder) Then(step *Tween) *SequenceBuilder

Then places step at the cursor, after every previous step, and advances the cursor to the step's end. Nil steps are ignored.

func (*SequenceBuilder) Wait

Wait inserts an interval of d before the next step.

func (*SequenceBuilder) With

func (b *SequenceBuilder) With(step *Tween) *SequenceBuilder

With places step so it runs in parallel with the last Then's step, starting at the same time. The cursor advances to the end of the longer of the parallel steps. Nil steps are ignored.

type Timeline

type Timeline struct {
	// contains filtered or unexported fields
}

Timeline coordinates multiple tweens and timed callback cues along a single deterministic clock, supporting seeking, forward and reverse playback, and looping. Its zero value is ready to use.

Example

A Timeline sequences tweens and calls: Append runs a tween after the previous one ends, and Add starts one at a set time.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/tween"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	var x, y float32
	tl := tween.NewTimeline().
		Append(tween.Float32(0, 100, time.Second, core.Linear, func(v float32) { x = v })).
		Append(tween.Float32(0, 50, 500*time.Millisecond, core.Linear, func(v float32) { y = v })).
		Call(time.Second, func() { fmt.Println("halfway cue") })
	fmt.Println(tl.Duration())
	tl.Play()
	tl.Update(1250 * time.Millisecond)
	fmt.Println(x, y, tl.Done())
	tl.Update(time.Second)
	fmt.Println(x, y, tl.Done())
}
Output:
1.5s
halfway cue
100 25 false
100 50 true

func NewTimeline

func NewTimeline() *Timeline

NewTimeline returns an empty Timeline ready to add tracks and cues to.

func (*Timeline) Add

func (tl *Timeline) Add(at time.Duration, tw *Tween) *Timeline

Add places tw on the timeline starting at offset at. Nil tweens are ignored; negative offsets are clamped to 0.

func (*Timeline) Append

func (tl *Timeline) Append(tw *Tween) *Timeline

Append places tw on the timeline starting at its current Duration. Nil tweens are ignored.

func (*Timeline) Call

func (tl *Timeline) Call(at time.Duration, fn func()) *Timeline

Call schedules fn to run when playback crosses timestamp at. Nil callbacks are ignored; negative offsets are clamped to 0.

func (*Timeline) Done

func (tl *Timeline) Done() bool

Done reports whether a non-looping timeline has reached the end of its playback direction.

func (*Timeline) Duration

func (tl *Timeline) Duration() time.Duration

Duration returns the total span of the timeline across all tracks and cues.

func (*Timeline) Pause

func (tl *Timeline) Pause()

Pause suspends playback at the current timestamp.

func (*Timeline) Play

func (tl *Timeline) Play()

Play starts or resumes playback in the current direction.

func (*Timeline) Playing

func (tl *Timeline) Playing() bool

Playing reports whether the timeline is currently playing.

func (*Timeline) Restart

func (tl *Timeline) Restart()

Restart jumps to the start of the current playback direction (0 forward, Duration in reverse), applies all tracks, and starts playing.

func (*Timeline) Reverse

func (tl *Timeline) Reverse(reverse bool)

Reverse sets whether playback runs backward (from Duration down to 0).

func (*Timeline) Seek

func (tl *Timeline) Seek(at time.Duration)

Seek moves the timeline to timestamp at (clamped to [0, Duration()]) and puts every track — before, during, and after its window — at the exact value it holds at that time without firing cues.

func (*Timeline) SetLoop

func (tl *Timeline) SetLoop(loop bool)

SetLoop sets whether playback wraps around on reaching the end.

func (*Timeline) SetLoops

func (tl *Timeline) SetLoops(n int)

SetLoops sets how many runs the timeline plays: n <= 0 wraps around forever (the same as SetLoop(true)), n == 1 plays once (the same as SetLoop(false)), and larger n wraps n-1 more times. Calling it while playing counts the remaining runs, including the current pass. Unless n is 1, setting loops clears a finished timeline's done state.

func (*Timeline) SetSpeed

func (tl *Timeline) SetSpeed(s float64)

SetSpeed scales every step by s, so the timeline runs in slow motion (0.25) or fast forward. A scale of 0 stops advancement; negative values and NaN are treated as 1.

func (*Timeline) Time

func (tl *Timeline) Time() time.Duration

Time returns the timeline's current playback timestamp.

func (*Timeline) Update

func (tl *Timeline) Update(dt time.Duration)

Update advances the timeline by dt when playing, updating tracks and firing any cues crossed during the step.

type Tween

type Tween struct {
	// contains filtered or unexported fields
}

Tween interpolates a value over a fixed duration using an easing function, advancing deterministically via Update(dt) on game.Loop steps.

func By

func By[T any](value *T, delta T, d time.Duration, ease Ease, add func(a, b T) T, lerp func(a, b T, t float64) T) *Tween

By returns a tween like To that animates *value to its value at step start plus delta. The start value is read lazily when the tween first runs, so relative steps compose with the results of earlier steps. add combines the start value with delta and lerp interpolates; pass nil for both to use the defaults for float32, float64, core.Point and core.Color. For other types add is required; without it the tween holds the start value and snaps to delta at the end.

func CameraFollowTransition

func CameraFollowTransition(cam *tilemap.Camera, target func() core.Point, d time.Duration, curve core.Curve) *Tween

CameraFollowTransition returns a tween that smoothly moves cam from its position when the tween starts onto a moving target position sampled from target each step, ending directly on target() (clamped to cam.Bounds if set).

func CameraMove

func CameraMove(cam *tilemap.Camera, toX, toY, toZoom, toRot float32, d time.Duration, curve core.Curve) *Tween

CameraMove returns a tween that moves cam simultaneously to (toX, toY), toZoom, and toRot over d with curve, clamping to cam.Bounds if set.

func CameraPan

func CameraPan(cam *tilemap.Camera, toX, toY float32, d time.Duration, curve core.Curve) *Tween

CameraPan returns a tween that pans cam from its position when the tween starts to (toX, toY) over d with curve, clamping to cam.Bounds if set.

func CameraRotate

func CameraRotate(cam *tilemap.Camera, toRot float32, d time.Duration, curve core.Curve) *Tween

CameraRotate returns a tween that rotates cam from its rotation when the tween starts to toRot (in radians) over d with curve, clamping to cam.Bounds if set.

func CameraZoom

func CameraZoom(cam *tilemap.Camera, toZoom float32, d time.Duration, curve core.Curve) *Tween

CameraZoom returns a tween that zooms cam from its zoom when the tween starts (treating <= 0 as 1) to toZoom over d with curve, clamping to cam.Bounds if set.

func Color

func Color(from, to core.Color, d time.Duration, curve core.Curve, set func(core.Color)) *Tween

Color returns a tween over a core.Color from from to to over d with curve, interpolating sRGB and alpha channels.

func Float32

func Float32(from, to float32, d time.Duration, curve core.Curve, set func(float32)) *Tween

Float32 returns a tween over a float32 value from from to to over d with curve.

Example

A Tween animates a value on the game's fixed step; Repeat with yoyo plays it back and forth.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/tween"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	alpha := float32(0)
	tw := tween.Float32(0, 1, time.Second, core.Linear, func(v float32) { alpha = v }).Repeat(1, true)
	for range 6 {
		tw.Update(400 * time.Millisecond)
		fmt.Printf("%.1f ", alpha)
	}
	fmt.Println(tw.Done())
}
Output:
0.4 0.8 0.8 0.4 0.0 0.0 true

func Float64

func Float64(from, to float64, d time.Duration, curve core.Curve, set func(float64)) *Tween

Float64 returns a tween over a float64 value from from to to over d with curve.

func Follow

func Follow(curve Curve, d time.Duration, ease core.Curve, set func(pos core.Point, angle float32)) *Tween

Follow returns a Tween that moves along curve by arc length over d with ease, calling set with the current position and tangent angle (in radians) on each step. A zero ease uses core.Linear. Negative d is treated as 0.

func FromCurrent

func FromCurrent[T any](get func() T, set func(T), to T, d time.Duration, ease Ease, lerp ...func(a, b T, t float64) T) *Tween

FromCurrent returns a tween like To over a value reached through get and set: the start is read from get when the step starts, and to is the target. A zero ease uses linear.

The built-in types (float32, float64, core.Point and core.Color) interpolate without a lerp; other types need one passed explicitly and hold their start value until snapping to the target at the end when lerp is omitted, matching New.

func New

func New[T any](from, to T, d time.Duration, curve core.Curve, lerp func(a, b T, t float64) T, set func(T)) *Tween

New returns a tween that interpolates from from to to over d with curve, using lerp to compute each intermediate value and set to apply it.

A zero curve uses core.Linear. A negative d is treated as 0.

func Point

func Point(from, to core.Point, d time.Duration, curve core.Curve, set func(core.Point)) *Tween

Point returns a tween over a core.Point from from to to over d with curve.

func To

func To[T any](value *T, to T, d time.Duration, ease Ease, lerp ...func(a, b T, t float64) T) *Tween

To returns a tween that animates *value from whatever it holds when the step starts to to over d with ease. The start value is read lazily when the tween first runs, not when it is built, so earlier steps can leave the value anywhere. A zero ease uses linear.

The built-in types (float32, float64, core.Point and core.Color) interpolate without a lerp; other types need one passed explicitly and hold their start value until snapping to the target at the end when lerp is omitted, matching New.

func (*Tween) Delay

func (t *Tween) Delay(d time.Duration) *Tween

Delay waits d before the tween begins moving. Negative durations are treated as 0.

func (*Tween) Done

func (t *Tween) Done() bool

Done reports whether the tween has reached its end.

func (*Tween) Duration

func (t *Tween) Duration() time.Duration

Duration returns the tween's total duration including delay and repeats. For a tween that repeats forever, Duration returns one full cycle (delay plus one pass, or two passes when yoyo is enabled).

func (*Tween) OnComplete

func (t *Tween) OnComplete(fn func()) *Tween

OnComplete registers fn to run once when Update finishes the tween. Multiple callbacks run in the order registered.

func (*Tween) Repeat

func (t *Tween) Repeat(count int, yoyo bool) *Tween

Repeat repeats the tween count additional times after its first pass (0 plays once; RepeatForever or any negative value repeats forever). When yoyo is true, alternating passes play back from to to from.

func (*Tween) Reset

func (t *Tween) Reset()

Reset rewinds the tween to its start so it can play again from elapsed 0. For tweens that capture their start lazily (To, By, FromCurrent, and the camera helpers), Reset clears the captured start so the next run reads the current value again.

func (*Tween) Seek

func (t *Tween) Seek(at time.Duration)

Seek moves the tween to timestamp at and applies the value it holds there without firing OnComplete callbacks. Unlike Reset, Seek(0) keeps any already-captured start value so scrubbing and timeline restarts remain deterministic.

func (*Tween) Update

func (t *Tween) Update(dt time.Duration) bool

Update advances the tween by dt, applies the value at the new time, and reports whether the tween has finished.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL