-
Notifications
You must be signed in to change notification settings - Fork 0
/
point.go
67 lines (54 loc) · 1.92 KB
/
point.go
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import "math"
type Point struct {
x float64
y float64
}
// Adds the coordinates of two points
func (p1 Point) Add(p2 Point) Point {
return Point{x: p1.x + p2.x, y: p1.y + p2.y}
}
// Subtracts the coordinates of two points
func (p1 Point) Subtract(p2 Point) Point {
return Point{x: p1.x - p2.x, y: p1.y - p2.y}
}
// Multiplies the coordinates of two points
func (p1 Point) Multiply(p2 Point) Point {
return Point{x: p1.x * p2.x, y: p1.y * p2.y}
}
// Adds a scalar value to the coordinates of a point
func (point Point) AddV(val float64) Point {
return Point{x: point.x + val, y: point.y + val}
}
// Multiplies the coordinates of a point by a scalar value
func (point Point) MultiplyV(val float64) Point {
return Point{x: point.x * val, y: point.y * val}
}
// Divides the coordinates of a point by a scalar value
func (point Point) DivideV(val float64) Point {
return Point{x: point.x / val, y: point.y / val}
}
// Clamps the coordinates of a point to the specified lower and upper bounds
func (point Point) Limit(lower, upper float64) Point {
return Point{x: math.Min(math.Max(point.x, lower), upper), y: math.Min(math.Max(point.y, lower), upper)}
}
// Calculates the distance between two points
func (p1 Point) Distance(p2 Point) float64 {
return math.Sqrt(math.Pow(p1.x-p2.x, 2) + math.Pow(p1.y-p2.y, 2))
}
// Normalize returns a new point with the same direction but with a magnitude of 1
func (p1 Point) Normalize() Point {
magnitude := math.Sqrt(math.Pow(p1.x, 2) + math.Pow(p1.y, 2))
return Point{x: math.Floor(p1.x/magnitude + 0.5), y: math.Floor(p1.y/magnitude + 0.5)}
}
// Linearly interpolates between two points by a given proportion
func (p1 Point) Lerp(p2 Point, proportion float64) Point {
return Point{
x: Lerp(p1.x, p2.x, proportion),
y: Lerp(p1.y, p2.y, proportion),
}
}
// Linearly interpolates between two values by a given proportion
func Lerp(p0, p1, t float64) float64 {
return (1-t)*p0 + t*p1
}