From 29b1220ec33da3573eb0dc6492cafc417b2ebf39 Mon Sep 17 00:00:00 2001 From: Ben Cragg Date: Thu, 4 Apr 2019 15:48:27 +0100 Subject: [PATCH] Setting order of returned points on Rect --- geometry.go | 8 +++++++- geometry_test.go | 20 ++------------------ 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/geometry.go b/geometry.go index b332f25..9b232bf 100644 --- a/geometry.go +++ b/geometry.go @@ -3,6 +3,7 @@ package pixel import ( "fmt" "math" + "sort" ) // Clamp returns x clamped to the interval [min, max]. @@ -610,7 +611,8 @@ func (r Rect) IntersectLine(l Line) Vec { } // IntersectionPoints returns all the points where the Rect intersects with the line provided. This can be zero, one or -// two points, depending on the location of the shapes. +// two points, depending on the location of the shapes. The points of intersection will be returned in order of +// closest-to-l.A to closest-to-l.B. func (r Rect) IntersectionPoints(l Line) []Vec { // Use map keys to ensure unique points pointMap := make(map[Vec]struct{}) @@ -625,6 +627,10 @@ func (r Rect) IntersectionPoints(l Line) []Vec { for point := range pointMap { points = append(points, point) } + + // Order the points + sort.Slice(points, func(i, j int) bool { return points[i].To(l.A).Len() < points[j].To(l.A).Len() }) + return points } diff --git a/geometry_test.go b/geometry_test.go index ebabfa0..2f214a7 100644 --- a/geometry_test.go +++ b/geometry_test.go @@ -839,16 +839,6 @@ func TestRect_IntersectCircle(t *testing.T) { } func TestRect_IntersectionPoints(t *testing.T) { - in := func(v pixel.Vec, vs []pixel.Vec) bool { - for _, vec := range vs { - if vec == v { - return true - } - } - - return false - } - type fields struct { Min pixel.Vec Max pixel.Vec @@ -887,14 +877,8 @@ func TestRect_IntersectionPoints(t *testing.T) { Min: tt.fields.Min, Max: tt.fields.Max, } - got := r.IntersectionPoints(tt.args.l) - if len(got) != len(tt.want) { - t.Errorf("Rect.IntersectPoints() has incorrect length. Expected %d, got %d", len(tt.want), len(got)) - } - for _, v := range got { - if !in(v, tt.want) { - t.Errorf("Rect.IntersectPoints(): got unexpected result = %v", v) - } + if got := r.IntersectionPoints(tt.args.l); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Rect.IntersectPoints() = %v, want %v", got, tt.want) } }) }