diff --git a/govector_test.go b/govector_test.go index bb24356..ddd2f26 100644 --- a/govector_test.go +++ b/govector_test.go @@ -119,16 +119,39 @@ func TestIntersection(t *testing.T) { t.Errorf("Intersection Error") } - p1 = Point2d{20, 5} - p2 = Point2d{5, 0} + p1 = Point2d{20, 5} + p2 = Point2d{5, 0} - v1 = Vector2d{10, 0} - v2 = Vector2d{0, 10} + 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") - } + i, p = Intersection(p1, p2, v1, v2) + fmt.Printf("%v %v\n", i, p) + if i { + t.Errorf("Intersection Error") + } +} + +func TestAngle(t *testing.T) { + v1 := Vector2d{10, 0} + v2 := Vector2d{0, 10} + + a := Angle(v2, v1) + + fmt.Printf("%v %v %f\n", v1, v2, a*rad2deg) + if math.Abs(a-math.Pi/2) > epsilon { + t.Errorf("Angle Error") + } + + v1 = Vector2d{5, 0} + v2 = Vector2d{10, 10} + + a = Angle(v1, v2) + + fmt.Printf("%v %v %f\n", v1, v2, a*rad2deg) + + if math.Abs(a-math.Pi/4) > epsilon { + t.Errorf("Angle Error") + } } diff --git a/vectorpoint.go b/vectorpoint.go index 704dddc..4f2222e 100644 --- a/vectorpoint.go +++ b/vectorpoint.go @@ -22,6 +22,7 @@ type Point2d struct { } const epsilon = 1e-7 +const rad2deg = 180 / math.Pi func (p1 Point2d) Sub(p2 Point2d) Vector2d { return Vector2d{p1.X - p2.X, p1.Y - p2.Y} @@ -80,3 +81,8 @@ func Move(d1, d2 Point2d, velocity float64, timeDelta float64) Point2d { func Distance(p1, p2 Point2d) float64 { return p1.Sub(p2).Mag() } + +func Angle(v1, v2 Vector2d) float64 { + x := (v1.Dot(v2) / (v1.Mag() * v2.Mag())) + return math.Acos(x) +}