forces.dart 1.7 KB
Newer Older
Matt Perry's avatar
Matt Perry committed
1 2 3 4 5
// 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.

import 'package:newton/newton.dart';
6

7
/// A factory for simulations
Matt Perry's avatar
Matt Perry committed
8
abstract class Force {
9 10
  const Force();

11
  Simulation release(double position, double velocity);
Matt Perry's avatar
Matt Perry committed
12 13
}

14
/// A factory for spring-based physics simulations
Matt Perry's avatar
Matt Perry committed
15
class SpringForce extends Force {
16
  const SpringForce(this.spring, { this.left: 0.0, this.right: 1.0 });
17

18
  /// The description of the spring to be used in the created simulations
Matt Perry's avatar
Matt Perry committed
19
  final SpringDescription spring;
20

21
  /// Where to put the spring's resting point when releasing left
22
  final double left;
23 24

  /// Where to put the spring's resting point when releasing right
25
  final double right;
Matt Perry's avatar
Matt Perry committed
26

27 28 29 30 31
  /// How pricely to terminate the simulation
  ///
  /// We overshoot the target by this distance, but stop the simulation when
  /// the spring gets within this distance (regardless of how fast it's moving).
  /// This causes the spring to settle a bit faster than it otherwise would.
32
  static const Tolerance tolerance = const Tolerance(
33 34 35 36
    velocity: double.INFINITY,
    distance: 0.01
  );

37
  Simulation release(double position, double velocity) {
38 39
    double target = velocity < 0.0 ? this.left - tolerance.distance
                                   : this.right + tolerance.distance;
40 41
    return new SpringSimulation(spring, position, target, velocity)
      ..tolerance = tolerance;
Matt Perry's avatar
Matt Perry committed
42 43 44
  }
}

45 46 47 48 49 50
final SpringDescription _kDefaultSpringDesc = new SpringDescription.withDampingRatio(
  mass: 1.0,
  springConstant: 500.0,
  ratio: 1.0
);

51
/// A spring force with reasonable default values
Matt Perry's avatar
Matt Perry committed
52
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);