confetty/physics/physics.go

79 lines
1.3 KiB
Go
Raw Normal View History

2021-08-07 02:00:08 +00:00
package physics
2021-08-07 18:43:40 +00:00
import (
"math"
)
2021-08-07 02:00:08 +00:00
2021-08-07 21:45:59 +00:00
type Position Point
2021-08-07 02:00:08 +00:00
type Velocity Vector
type Acceleration Vector
var Gravity = Acceleration{
X: 0,
Y: 9.81,
}
2021-08-07 18:43:40 +00:00
type Motion struct {
2021-08-07 02:00:08 +00:00
pos Position
vel Velocity
acc Acceleration
2021-08-07 18:43:40 +00:00
}
type Physics struct {
current Motion
initial Motion
fps float64
2021-08-07 02:00:08 +00:00
}
type Vector struct {
X float64
Y float64
}
2021-08-07 21:45:59 +00:00
type Point struct {
X float64
Y float64
}
// Distance calculates the euclidean distance between two points
func (a Point) Distance(b Point) float64 {
return math.Sqrt(math.Pow(b.X-a.X, 2) + math.Pow(b.Y-a.Y, 2))
}
func New(pos Point, vel, acc Vector, fps float64) *Physics {
2021-08-07 18:43:40 +00:00
motion := Motion{
2021-08-07 02:00:08 +00:00
pos: Position(pos),
vel: Velocity(vel),
acc: Acceleration(acc),
}
2021-08-07 18:43:40 +00:00
return &Physics{
initial: motion,
current: motion,
fps: fps,
}
}
func (p *Physics) Reset() {
p.current = p.initial
2021-08-07 02:00:08 +00:00
}
func (p *Physics) Update() {
2021-08-08 00:04:23 +00:00
p.current.pos.X += p.current.vel.X / p.fps
p.current.pos.Y += p.current.vel.Y / p.fps
p.current.vel.X += p.current.acc.X / p.fps
p.current.vel.Y += p.current.acc.Y / p.fps
2021-08-07 02:00:08 +00:00
}
2021-08-07 21:45:59 +00:00
func (p Physics) Displacement() float64 {
return Point(p.initial.pos).Distance(Point(p.current.pos))
}
2021-08-07 02:00:08 +00:00
func (p Physics) PosX() int {
2021-08-07 18:43:40 +00:00
return int(math.Round(p.current.pos.X))
2021-08-07 02:00:08 +00:00
}
func (p Physics) PosY() int {
2021-08-07 18:43:40 +00:00
return int(math.Round(p.current.pos.Y))
2021-08-07 02:00:08 +00:00
}