OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 part of dart.math; |
| 5 |
| 6 /** |
| 7 * A utility class for representing two-dimensional positions. |
| 8 */ |
| 9 class Point<T extends num> { |
| 10 final T x; |
| 11 final T y; |
| 12 |
| 13 const Point([T x = 0, T y = 0]): this.x = x, this.y = y; |
| 14 |
| 15 String toString() => 'Point($x, $y)'; |
| 16 |
| 17 bool operator ==(other) { |
| 18 if (other is !Point) return false; |
| 19 return x == other.x && y == other.y; |
| 20 } |
| 21 |
| 22 int get hashCode => _JenkinsSmiHash.hash2(x.hashCode, y.hashCode); |
| 23 |
| 24 /** |
| 25 * Add [other] to `this`, as if both points were vectors. |
| 26 * |
| 27 * Returns the resulting "vector" as a Point. |
| 28 */ |
| 29 Point<T> operator +(Point<T> other) { |
| 30 return new Point<T>(x + other.x, y + other.y); |
| 31 } |
| 32 |
| 33 /** |
| 34 * Subtract [other] from `this`, as if both points were vectors. |
| 35 * |
| 36 * Returns the resulting "vector" as a Point. |
| 37 */ |
| 38 Point<T> operator -(Point<T> other) { |
| 39 return new Point<T>(x - other.x, y - other.y); |
| 40 } |
| 41 |
| 42 /** |
| 43 * Scale this point by [factor] as if it was a vector. |
| 44 * |
| 45 * *Important* *Note*: This function accepts a `num` as its argument only so |
| 46 * that you can scale Point<double> objects by an `int` factor. Because the |
| 47 * star operator always returns the same type of Point that originally called |
| 48 * it, passing in a double [factor] on a `Point<int>` _causes_ _a_ |
| 49 * _runtime_ _error_ in checked mode. |
| 50 */ |
| 51 Point<T> operator *(num factor) { |
| 52 return new Point<T>(x * factor, y * factor); |
| 53 } |
| 54 |
| 55 /** |
| 56 * Get the straight line (Euclidean) distance between the origin (0, 0) and |
| 57 * this point. |
| 58 */ |
| 59 double get magnitude => sqrt(x * x + y * y); |
| 60 |
| 61 /** |
| 62 * Returns the distance between `this` and [other]. |
| 63 */ |
| 64 double distanceTo(Point<T> other) { |
| 65 var dx = x - other.x; |
| 66 var dy = y - other.y; |
| 67 return sqrt(dx * dx + dy * dy); |
| 68 } |
| 69 |
| 70 /** |
| 71 * Returns the squared distance between `this` and [other]. |
| 72 * |
| 73 * Squared distances can be used for comparisons when the actual value is not |
| 74 * required. |
| 75 */ |
| 76 T squaredDistanceTo(Point<T> other) { |
| 77 var dx = x - other.x; |
| 78 var dy = y - other.y; |
| 79 return dx * dx + dy * dy; |
| 80 } |
| 81 } |
OLD | NEW |