server/obstacle.go

90 lines
2.2 KiB
Go
Raw Normal View History

2014-04-23 14:28:13 -07:00
package server
2013-10-25 22:30:15 -07:00
import (
"encoding/json"
"math"
2013-10-25 22:30:15 -07:00
"math/rand"
v "hackerbots.us/vector"
2013-10-25 22:30:15 -07:00
)
2014-04-14 00:26:41 -07:00
// Obstacle is the implementation of the generic building type in the game.
2013-10-25 22:30:15 -07:00
type Obstacle struct {
2013-11-24 14:26:40 -08:00
Bounds v.AABB2d `json:"bounds"`
Hp int `json:"-"`
2013-10-25 22:30:15 -07:00
}
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
}
2014-04-26 14:56:12 -07:00
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()))
2014-04-14 00:39:42 -07:00
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()))
2014-04-26 14:56:12 -07:00
return dist
}
func obstacleFromValues(x, y, w, h float64, hp int) (o Obstacle) {
return Obstacle{
Bounds: v.AABB2d{
A: v.Point2d{X: x, Y: y},
B: v.Point2d{X: x + w, Y: y + h},
},
Hp: hp,
}
}
2014-04-14 00:26:41 -07:00
// GenerateObstacles returns a slice of (count) obstacles within a region
// bounded by width, height.
2014-04-26 14:56:12 -07:00
func GenerateObstacles(count int, width, height float64) []Obstacle {
2013-10-25 22:30:15 -07:00
out := []Obstacle{}
// Create obstacles that cover the edges of the world, so we don't need to
// special case collision at the edges
// left wall
out = append(out, obstacleFromValues(0, 5, 5, height-10, 0))
// // right wall
out = append(out, obstacleFromValues(width-5, 5, 5, height-10, 0))
// // top wall
out = append(out, obstacleFromValues(0, height-5, width, 5, 0))
// bottom wall
out = append(out, obstacleFromValues(0, 0, width, 5, 0))
// Now create N random objects somewhere in the world
2013-10-25 22:30:15 -07:00
for i := 0; i < count; i++ {
2014-04-26 14:56:12 -07:00
x := rand.Float64() * (width - (width / 10))
y := rand.Float64() * (height - (height / 10))
w := rand.Float64()*(width/10) + 20
h := rand.Float64()*(height/10) + 20
2013-10-25 22:30:15 -07:00
out = append(
out,
obstacleFromValues(x, y, w, h, 10000))
2013-10-25 22:30:15 -07:00
}
return out
}