Created
August 15, 2023 17:12
-
-
Save kalexmills/2176965208d168e605bd46ccf54b0b0b to your computer and use it in GitHub Desktop.
A Simple Path struct for moving between points in sequence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Path represents a looping sequence of points which are interpolated between. | |
// FIXME: this doesn't loop properly at the moment. It will need to be recreated whenever the animation completes. | |
type Path struct { | |
sequence *gween.Sequence | |
points []image.Point | |
idx int | |
} | |
// NewPath constructs a static sequence with no motion, and the delay between the current point and the next. | |
func NewPath(startPoint image.Point) *Path { | |
return &Path{ | |
points: []image.Point{startPoint}, | |
sequence: gween.NewSequence(), | |
} | |
} | |
func (s *Path) EaseTo(to image.Point, timeSeconds float32, ease ease.TweenFunc) *Path { | |
s.sequence.Add(gween.New(0, 1, timeSeconds, ease)) | |
s.points = append(s.points, to) | |
return s | |
} | |
// Loop causes the sequence to loop back to the beginning -- creating an infinite loop. | |
func (s *Path) Loop(timeSeconds float32, ease ease.TweenFunc) *Path { | |
s.sequence.Add(gween.New(0, 1, timeSeconds, ease)) | |
s.sequence.SetLoop(1) | |
return s | |
} | |
func (s *Path) Wait(timeSeconds float32) *Path { | |
s.sequence.Add(gween.New(0, 1, timeSeconds, ease.Linear)) | |
s.points = append(s.points, s.points[len(s.points)-1]) | |
return s | |
} | |
func (s *Path) Update(dt float32) (pt image.Point, tweenDone, seqDone bool) { | |
if !s.sequence.HasTweens() { | |
return s.points[0], false, true | |
} | |
v, tweenDone, seqDone := s.sequence.Update(dt) | |
if tweenDone { | |
s.idx = (s.idx + 1) % len(s.points) | |
} | |
i, j := s.idx, (s.idx+1)%len(s.points) | |
x := int(math.Round(float64((1-v)*float32(s.points[i].X) + v*float32(s.points[j].X)))) | |
y := int(math.Round(float64((1-v)*float32(s.points[i].Y) + v*float32(s.points[j].Y)))) | |
return image.Pt(x, y), tweenDone, seqDone | |
} | |
func (s *Path) String() string { | |
var b strings.Builder | |
b.WriteString("\n") | |
for idx, s := range s.sequence.Tweens { | |
b.WriteString(fmt.Sprintf("\t%d: %#v\n", idx, s)) | |
} | |
return fmt.Sprintf("seq: %v\npts: %v\nidx: %d", b.String(), s.points, s.idx) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment