Added dot product, cross product and intersection test

This commit is contained in:
Fraser Graham 2013-08-09 14:49:52 -07:00 committed by Fraser Graham
parent 68842de56e
commit 88f2a38d1a
2 changed files with 83 additions and 0 deletions

View File

@ -2,6 +2,7 @@ package govector
import ( import (
"fmt" "fmt"
"math"
"testing" "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")
}
}

View File

@ -43,6 +43,24 @@ func (v Vector2d) Scale(s float64) Vector2d {
return Vector2d{v.X * s, v.Y * s} 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 { func (v Vector2d) Normalize() Vector2d {
if v.X == 0 && v.Y == 0 { if v.X == 0 && v.Y == 0 {
return v return v