gg/mx/vector.go
2024-05-28 13:24:12 +05:00

112 lines
1.6 KiB
Go

package mx
import (
//"github.com/hajimehoshi/ebiten/v2"
"math"
)
var (
ZV = V2(0)
)
type Vector struct {
X, Y Float
}
type Vectors []Vector
func (v Vector) XY() (Float, Float) {
return v.X, v.Y
}
func V(x, y Float) Vector {
return Vector{x, y}
}
func V2(v Float) Vector {
return Vector{v, v}
}
func VX(x Float) Vector {
return Vector{x, 0}
}
func VY(y Float) Vector {
return Vector{0, y}
}
func (v Vector) Div(o Vector) Vector {
return V(
v.X / o.X,
v.Y / o.Y,
)
}
func (v Vector) Mul(o Vector) Vector {
return V(
v.X * o.X,
v.Y * o.Y,
)
}
func (v Vector) Eq(o Vector) bool {
return v.X == o.X && v.Y == o.Y
}
// Returns the vector with the matrix applied
func (v Vector) Apply(m Matrice) Vector {
x, y := m.Apply(v.X, v.Y)
return Vector{x, y}
}
// Adds the vector to other one returning the result.
func (v Vector) Add(a Vector) Vector {
v.X += a.X
v.Y += a.Y
return v
}
// Returns the subtraction of all the vectors from the current one.
func (v Vector) Sub(s Vector) Vector {
v.X -= s.X
v.Y -= s.Y
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.
func (v Vector) Rot(a Float) Vector {
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)
}
func (pts Vectors) PointsContainedIn(
c PointContainer,
) Vectors {
ret := make(Vectors, 0, len(pts))
for _, pt := range pts {
if c.ContainsPoint(pt) {
ret = append(ret, pt)
}
}
return ret
}