Line data Source code
1 : import 'dart:math'; 2 : 3 : import '../../extensions.dart'; 4 : 5 : /// This represents a line on the ax + by = c form 6 : /// If you just want to represent a part of a line, look into LineSegment. 7 : class Line { 8 : final double a; 9 : final double b; 10 : final double c; 11 : 12 4 : const Line(this.a, this.b, this.c); 13 : 14 3 : static Line fromPoints(Vector2 p1, Vector2 p2) { 15 9 : final a = p2.y - p1.y; 16 9 : final b = p1.x - p2.x; 17 21 : final c = p2.y * p1.x - p1.y * p2.x; 18 3 : return Line(a, b, c); 19 : } 20 : 21 : /// Returns an empty list if there is no intersection 22 : /// If the lines are concurrent it returns one point in the list. 23 : /// If they coincide it returns an empty list as well 24 3 : List<Vector2> intersections(Line otherLine) { 25 21 : final determinant = a * otherLine.b - otherLine.a * b; 26 3 : if (determinant == 0) { 27 : //The lines are parallel (potentially coincides) and have no intersection 28 3 : return []; 29 : } 30 3 : return [ 31 3 : Vector2( 32 24 : (otherLine.b * c - b * otherLine.c) / determinant, 33 24 : (a * otherLine.c - otherLine.a * c) / determinant, 34 : ), 35 : ]; 36 : } 37 : 38 : /// The angle of this line in relation to the x-axis 39 0 : double get angle => atan2(-a, b); 40 : 41 0 : @override 42 : String toString() { 43 0 : final ax = '${a}x'; 44 0 : final by = b.isNegative ? '${b}y' : '+${b}y'; 45 0 : return '$ax$by=$c'; 46 : } 47 : }