Skip to content

Commit

Permalink
Merge pull request #290 from dusk125/master
Browse files Browse the repository at this point in the history
Fixing #277: Rect.Intersect and Rect.Intersects now have consistent behavior
  • Loading branch information
dusk125 committed Aug 19, 2021
2 parents 4964768 + 1597215 commit d940a42
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 23 deletions.
8 changes: 4 additions & 4 deletions rectangle.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,10 @@ func (r Rect) Intersect(s Rect) Rect {
// This function is overall about 5x faster than Intersect, so it is better
// to use if you have no need for the returned Rect from Intersect.
func (r Rect) Intersects(s Rect) bool {
return !(s.Max.X < r.Min.X ||
s.Min.X > r.Max.X ||
s.Max.Y < r.Min.Y ||
s.Min.Y > r.Max.Y)
return !(s.Max.X <= r.Min.X ||
s.Min.X >= r.Max.X ||
s.Max.Y <= r.Min.Y ||
s.Min.Y >= r.Max.Y)
}

// IntersectCircle returns a minimal required Vector, such that moving the rect by that vector would stop the Circle
Expand Down
66 changes: 47 additions & 19 deletions rectangle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,28 +329,56 @@ func TestRect_IntersectionPoints(t *testing.T) {
}
}

func BenchmarkRect_Intersect(b *testing.B) {
root := pixel.R(10, 10, 50, 50)
inter := pixel.R(11, 11, 15, 15)

for i := 0; i < b.N; i++ {
if root.Intersect(inter) != pixel.ZR {
// do a thing
}
var rectIntTests = []struct {
name string
r1, r2 pixel.Rect
want pixel.Rect
intersect bool
}{
{
name: "Nothing touching",
r1: pixel.R(0, 0, 10, 10),
r2: pixel.R(21, 21, 40, 40),
want: pixel.ZR,
},
{
name: "Edge touching",
r1: pixel.R(0, 0, 10, 10),
r2: pixel.R(10, 10, 20, 20),
want: pixel.ZR,
},
{
name: "Bit of overlap",
r1: pixel.R(0, 0, 10, 10),
r2: pixel.R(0, 9, 20, 20),
want: pixel.R(0, 9, 10, 10),
intersect: true,
},
{
name: "Fully overlapped",
r1: pixel.R(0, 0, 10, 10),
r2: pixel.R(0, 0, 10, 10),
want: pixel.R(0, 0, 10, 10),
intersect: true,
},
}

// do a thing
func TestRect_Intersect(t *testing.T) {
for _, tt := range rectIntTests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.r1.Intersect(tt.r2); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Rect.Intersect() = %v, want %v", got, tt.want)
}
})
}
}

func BenchmarkRect_IsIntersect(b *testing.B) {
root := pixel.R(10, 10, 50, 50)
inter := pixel.R(11, 11, 15, 15)

for i := 0; i < b.N; i++ {
if root.Intersects(inter) {
// do a thing
}

// do a thing
func TestRect_Intersects(t *testing.T) {
for _, tt := range rectIntTests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.r1.Intersects(tt.r2); got != tt.intersect {
t.Errorf("Rect.Intersects() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit d940a42

Please sign in to comment.