aboutsummaryrefslogtreecommitdiff
path: root/physics/geometry.go
blob: 07a41e36078333c7c6ae0dd502fa85aa593a39d2 (plain) (blame)
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

package physics

import (
	"image"
	"math"
)

type Point = image.Point
type Rectangle = image.Rectangle

func Distance(p1, p2 Point) float64 {
	return math.Sqrt(math.Pow(float64(p1.X-p2.X), 2) + math.Pow(float64(p1.Y-p2.Y), 2))
}

func Length(p Point) float64 {
	return Distance(p, Point{X: 0, Y: 0})
}

func Normalize(p Point) Point {
	return p.Div(int(Length(p)))
}

func Translate(r Rectangle, offset Point) Rectangle {
	return Rectangle{
		Min: r.Min.Add(offset),
		Max: r.Max.Add(offset),
	}
}

func AdjacentPoints(from Point) []Point {
	return []Point{
		from.Add(Point{X: 0, Y: -100}),
		from.Add(Point{X: 0, Y: 100}),
		from.Add(Point{X: -100, Y: 0}),
		from.Add(Point{X: 100, Y: 0}),
	}
}

func Closest(from Point, candidates []Point, moveMap MoveMap) (Point, int) {
	var closest Point
	closestDistance := math.MaxInt
	for _, dest := range candidates {
		path, ok := SearchPath(from, dest, moveMap)
		if !ok {
			continue
		}
		if len(path) < closestDistance {
			closest = dest
			closestDistance = len(path)
		}
	}
	return closest, closestDistance
}