From 88f2a38d1a6cd318bad0e70ab3f1214418643bd4 Mon Sep 17 00:00:00 2001 From: Fraser Graham Date: Fri, 9 Aug 2013 14:49:52 -0700 Subject: [PATCH] Added dot product, cross product and intersection test --- govector_test.go | 65 ++++++++++++++++++++++++++++++++++++++++++++++++ vectorpoint.go | 18 ++++++++++++++ 2 files changed, 83 insertions(+) diff --git a/govector_test.go b/govector_test.go index 42d066f..bb24356 100644 --- a/govector_test.go +++ b/govector_test.go @@ -2,6 +2,7 @@ package govector import ( "fmt" + "math" "testing" ) @@ -67,3 +68,67 @@ func TestNormalize(t *testing.T) { } } + +func TestDot(t *testing.T) { + v1 := Vector2d{0, 5} + v2 := Vector2d{5, 0} + d := v1.Dot(v2) + + if d != 0 { + t.Errorf("Dot Error") + } + + v1 = Vector2d{1, 5} + v2 = Vector2d{5, 0} + d = v1.Dot(v2) + + if d < 0 { + t.Errorf("Dot Error") + } + + v1 = Vector2d{-1, 5} + v2 = Vector2d{5, 0} + d = v1.Dot(v2) + + if d > 0 { + t.Errorf("Dot Error") + } + + v1 = Vector2d{5, 5} + v2 = Vector2d{5, 0} + v1 = v1.Normalize() + v2 = v2.Normalize() + d = v1.Dot(v2) + fmt.Printf("%v\n", d) + + if math.Abs(d-math.Acos(math.Pi/4)) < 0.0001 { + t.Errorf("Dot Error") + } +} + +func TestIntersection(t *testing.T) { + p1 := Point2d{0, 5} + p2 := Point2d{5, 0} + + v1 := Vector2d{10, 0} + v2 := Vector2d{0, 10} + + i, p := Intersection(p1, p2, v1, v2) + fmt.Printf("%v %v\n", i, p) + if !i { + t.Errorf("Intersection Error") + } + + p1 = Point2d{20, 5} + p2 = Point2d{5, 0} + + v1 = Vector2d{10, 0} + v2 = Vector2d{0, 10} + + i, p = Intersection(p1, p2, v1, v2) + fmt.Printf("%v %v\n", i, p) + if i { + t.Errorf("Intersection Error") + } + +} diff --git a/vectorpoint.go b/vectorpoint.go index 450323a..ccf2dcd 100644 --- a/vectorpoint.go +++ b/vectorpoint.go @@ -43,6 +43,24 @@ func (v Vector2d) Scale(s float64) Vector2d { return Vector2d{v.X * s, v.Y * s} } +func (v1 Vector2d) Cross(v2 Vector2d) float64 { + return v1.X*v2.Y - v1.Y*v2.X +} + +func (v1 Vector2d) Dot(v2 Vector2d) float64 { + return (v1.X * v2.X) + (v1.Y * v2.Y) +} + +func Intersection(p1, p2 Point2d, v1, v2 Vector2d) (bool, Point2d) { + t := p2.Sub(p1).Cross(v2) / v1.Cross(v2) + s := p2.Sub(p1).Cross(v1) / v1.Cross(v2) + if t >= 0 && t <= 1 && s >= 0 && s <= 1 { + return true, p1.Add(v1.Scale(t)) + } + + return false, Point2d{0, 0} +} + func (v Vector2d) Normalize() Vector2d { if v.X == 0 && v.Y == 0 { return v