-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.go
More file actions
46 lines (36 loc) · 959 Bytes
/
vector.go
File metadata and controls
46 lines (36 loc) · 959 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main
import (
"math"
)
// A 2d Vector
type Vector struct {
X, Y float64
}
func (v1 Vector) Equals(v2 Vector) bool {
return (v1.X == v2.X) && (v1.Y == v2.Y)
}
// Vector equals function that accounts for floating point noise
func (v1 Vector) NearlyEquals(v2 Vector, epsilon float64) bool {
return math.Abs(v1.X-v2.X) < epsilon && math.Abs(v1.Y-v2.Y) < epsilon
}
// All the following mathematical functions can be used as the following:
// v1 = Vector{1,2}
// v2 = Vector{3,4}
//
// sum = v1.Add(v2)
func (v1 Vector) Add(v2 Vector) Vector {
return Vector{v1.X + v2.X, v1.Y + v2.Y}
}
func (v1 Vector) Subtract(v2 Vector) Vector {
return Vector{v1.X - v2.X, v1.Y - v2.Y}
}
func (v Vector) Scale(scalar float64) Vector {
return Vector{v.X * scalar, v.Y * scalar}
}
func (v Vector) Magnitude() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func (v Vector) Normalize() Vector {
mag := v.Magnitude()
return Vector{v.X / mag, v.Y / mag}
}