Setting order of returned points on Rect

This commit is contained in:
Ben Cragg 2019-04-04 15:48:27 +01:00
parent 364a7a84ae
commit 29b1220ec3
2 changed files with 9 additions and 19 deletions

View File

@ -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
}

View File

@ -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)
}
})
}