package server import ( "encoding/json" "math" "math/rand" v "hackerbots.us/vector" ) // Obstacle is the implementation of the generic building type in the game. type Obstacle struct { Bounds v.AABB2d `json:"bounds"` Hp int `json:"-"` } func (o *Obstacle) MarshalJSON() ([]byte, error) { payload := [4]float64{ o.Bounds.A.X, o.Bounds.A.Y, o.Bounds.B.X, o.Bounds.B.Y, } return json.Marshal(payload) } func (o *Obstacle) UnmarshalJSON(incoming []byte) error { payload := [4]float64{} err := json.Unmarshal(incoming, &payload) if err != nil { return err } o.Bounds = v.AABB2d{ A: v.Point2d{X: payload[0], Y: payload[1]}, B: v.Point2d{X: payload[2], Y: payload[3]}, } return nil } func (o Obstacle) distance_from_point(p v.Point2d) float64 { dist := math.MaxFloat32 dist = math.Min(dist, float64(p.Sub(o.Bounds.A).Mag())) dist = math.Min(dist, float64(p.Sub(o.Bounds.B).Mag())) dist = math.Min(dist, float64(p.Sub(v.Point2d{X: o.Bounds.A.X, Y: o.Bounds.B.Y}).Mag())) dist = math.Min(dist, float64(p.Sub(v.Point2d{X: o.Bounds.B.X, Y: o.Bounds.A.Y}).Mag())) return dist } // GenerateObstacles returns a slice of (count) obstacles within a region // bounded by width, height. func GenerateObstacles(count int, width, height float64) []Obstacle { out := []Obstacle{} for i := 0; i < count; i++ { x := rand.Float64() * (width - (width / 10)) y := rand.Float64() * (height - (height / 10)) w := rand.Float64() * (width / 10) h := rand.Float64() * (height / 10) out = append( out, Obstacle{ Bounds: v.AABB2d{ A: v.Point2d{X: x, Y: y}, B: v.Point2d{X: 20 + x + w, Y: 20 + y + h}, }, Hp: 10000, }) } return out }