gg/mx/vector.go

113 lines
1.6 KiB
Go
Raw Normal View History

2024-05-28 11:24:12 +03:00
package mx
import (
//"github.com/hajimehoshi/ebiten/v2"
"math"
)
2023-12-24 15:05:34 +03:00
var (
ZV = V2(0)
)
type Vector struct {
X, Y Float
2024-05-28 11:24:12 +03:00
}
2024-05-28 11:24:12 +03:00
type Vectors []Vector
2024-01-13 18:17:34 +03:00
func (v Vector) XY() (Float, Float) {
return v.X, v.Y
}
2023-06-03 11:25:19 +03:00
func V(x, y Float) Vector {
return Vector{x, y}
}
2023-12-24 15:05:34 +03:00
func V2(v Float) Vector {
2024-01-18 06:06:27 +03:00
return Vector{v, v}
}
2024-05-28 11:24:12 +03:00
func VX(x Float) Vector {
2024-01-18 06:06:27 +03:00
return Vector{x, 0}
}
2024-05-28 11:24:12 +03:00
func VY(y Float) Vector {
2024-01-18 06:06:27 +03:00
return Vector{0, y}
2023-12-23 00:09:07 +03:00
}
func (v Vector) Div(o Vector) Vector {
return V(
v.X / o.X,
v.Y / o.Y,
)
}
2024-01-18 06:06:27 +03:00
func (v Vector) Mul(o Vector) Vector {
2023-12-23 00:09:07 +03:00
return V(
v.X * o.X,
v.Y * o.Y,
)
}
2023-06-10 17:43:04 +03:00
func (v Vector) Eq(o Vector) bool {
return v.X == o.X && v.Y == o.Y
}
// Returns the vector with the matrix applied
2024-05-28 11:24:12 +03:00
func (v Vector) Apply(m Matrice) Vector {
x, y := m.Apply(v.X, v.Y)
return Vector{x, y}
}
2023-05-30 14:34:10 +03:00
// Adds the vector to other one returning the result.
2024-05-28 11:24:12 +03:00
func (v Vector) Add(a Vector) Vector {
v.X += a.X
v.Y += a.Y
2023-05-30 14:34:10 +03:00
return v
}
// Returns the subtraction of all the vectors from the current one.
2024-05-28 11:24:12 +03:00
func (v Vector) Sub(s Vector) Vector {
v.X -= s.X
v.Y -= s.Y
2023-05-30 14:34:10 +03:00
return v
}
// Returns the negative version of the vector.
func (v Vector) Neg() Vector {
return Vector{
-v.X,
-v.Y,
}
}
// Returns the vector rotated by "a" angle in radians.
2024-01-18 06:06:27 +03:00
func (v Vector) Rot(a Float) Vector {
2024-05-28 11:24:12 +03:00
m := Matrice{}
m.Rotate(a)
return v.Apply(m)
}
// Returns the normalized vector.
func (v Vector) Norm() Vector {
l := math.Sqrt(v.X*v.X + v.Y*v.Y)
return V(v.X / l, v.Y / l)
}
2023-06-03 11:25:19 +03:00
2024-05-28 11:24:12 +03:00
func (pts Vectors) PointsContainedIn(
c PointContainer,
) Vectors {
ret := make(Vectors, 0, len(pts))
2023-06-03 11:25:19 +03:00
for _, pt := range pts {
2024-05-28 11:24:12 +03:00
if c.ContainsPoint(pt) {
2023-06-03 11:25:19 +03:00
ret = append(ret, pt)
}
}
return ret
}