Skip to content

Commit ca6dee4

Browse files
committed
added 2d vector math
1 parent 9aa3545 commit ca6dee4

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

math.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package sketchy
2+
3+
import "math"
4+
5+
type Vec2 struct {
6+
X float64
7+
Y float64
8+
}
9+
10+
func (v Vec2) Add(u Vec2) Vec2 {
11+
return Vec2{X: v.X + u.X, Y: v.Y + u.Y}
12+
}
13+
14+
func (v Vec2) Sub(u Vec2) Vec2 {
15+
return Vec2{X: v.X - u.X, Y: v.Y - u.Y}
16+
}
17+
18+
func (v Vec2) Scale(s float64) Vec2 {
19+
return Vec2{X: s * v.X, Y: s * v.Y}
20+
}
21+
22+
func (v Vec2) Dot(u Vec2) float64 {
23+
return v.X*u.X + v.Y*u.Y
24+
}
25+
26+
func (v Vec2) Mag() float64 {
27+
return math.Sqrt(math.Pow(v.X, 2) + math.Pow(v.Y, 2))
28+
}
29+
30+
func (v Vec2) Normalize() Vec2 {
31+
m := v.Mag()
32+
if m == 0 {
33+
panic("cannot normalize vector with zero magnitude")
34+
}
35+
return v.Scale(1 / m)
36+
}
37+
38+
func (v Vec2) UnitNormal() Vec2 {
39+
m := v.Mag()
40+
return Vec2{X: v.Y / m, Y: -v.X / m}
41+
}

0 commit comments

Comments
 (0)