action_spline.dart 2.19 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
part of flutter_sprites;
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Point _cardinalSplineAt(Point p0, Point p1, Point p2, Point p3, double tension, double t) {
  double t2 = t * t;
  double t3 = t2 * t;

  double s = (1.0 - tension) / 2.0;

  double b1 = s * ((-t3 + (2.0 * t2)) - t);
	double b2 = s * (-t3 + t2) + (2.0 * t3 - 3.0 * t2 + 1.0);
	double b3 = s * (t3 - 2.0 * t2 + t) + (-2.0 * t3 + 3.0 * t2);
	double b4 = s * (t3 - t2);

  double x = p0.x * b1 + p1.x * b2 + p2.x * b3 + p3.x * b4;
	double y = p0.y * b1 + p1.y * b2 + p2.y * b3 + p3.y * b4;

  return new Point(x, y);
}

24
/// Signature for callbacks used by the [ActionSpline] to set a [Point] value.
Hixie's avatar
Hixie committed
25 26
typedef void PointSetterCallback(Point value);

27 28
/// The spline action is used to animate a point along a spline definied by
/// a set of points.
29
class ActionSpline extends ActionInterval {
30 31 32 33 34

  /// Creates a new spline action with a set of points. The [setter] is a
  /// callback for setting the positions, [points] define the spline, and
  /// [duration] is the time for the action to complete. Optionally a [curve]
  /// can be used for easing.
35 36 37 38
  ActionSpline(this.setter, this.points, double duration, [Curve curve]) : super(duration, curve) {
    _dt = 1.0 / (points.length - 1.0);
  }

39
  /// The callback used to update a point when the action is run.
Hixie's avatar
Hixie committed
40
  final PointSetterCallback setter;
41 42

  /// A list of points that define the spline.
43
  final List<Point> points;
44 45

  /// The tension of the spline, defines the roundness of the curve.
46
  double tension = 0.5;
47 48 49

  double _dt;

50
  @override
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  void update(double t) {

    int p;
    double lt;

    if (t < 0.0) t = 0.0;

    if (t >= 1.0) {
      p = points.length - 1;
      lt = 1.0;
    } else {
      p = (t / _dt).floor();
      lt = (t - _dt * p) / _dt;
    }

    Point p0 = points[(p - 1).clamp(0, points.length - 1)];
    Point p1 = points[(p + 0).clamp(0, points.length - 1)];
    Point p2 = points[(p + 1).clamp(0, points.length - 1)];
    Point p3 = points[(p + 2).clamp(0, points.length - 1)];

    Point newPos = _cardinalSplineAt(p0, p1, p2, p3, tension, lt);

    setter(newPos);
  }
}