No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

obstacle.go 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package server
  2. import (
  3. "encoding/json"
  4. "math"
  5. "math/rand"
  6. v "hackerbots.us/vector"
  7. )
  8. // Obstacle is the implementation of the generic building type in the game.
  9. type Obstacle struct {
  10. Bounds v.AABB2d `json:"bounds"`
  11. Hp int `json:"-"`
  12. }
  13. func (o *Obstacle) MarshalJSON() ([]byte, error) {
  14. payload := [4]float64{
  15. o.Bounds.A.X,
  16. o.Bounds.A.Y,
  17. o.Bounds.B.X,
  18. o.Bounds.B.Y,
  19. }
  20. return json.Marshal(payload)
  21. }
  22. func (o *Obstacle) UnmarshalJSON(incoming []byte) error {
  23. payload := [4]float64{}
  24. err := json.Unmarshal(incoming, &payload)
  25. if err != nil {
  26. return err
  27. }
  28. o.Bounds = v.AABB2d{
  29. A: v.Point2d{X: payload[0], Y: payload[1]},
  30. B: v.Point2d{X: payload[2], Y: payload[3]},
  31. }
  32. return nil
  33. }
  34. func (o Obstacle) distance_from_point(p v.Point2d) float64 {
  35. dist := math.MaxFloat32
  36. dist = math.Min(dist, float64(p.Sub(o.Bounds.A).Mag()))
  37. dist = math.Min(dist, float64(p.Sub(o.Bounds.B).Mag()))
  38. dist = math.Min(dist, float64(p.Sub(v.Point2d{X: o.Bounds.A.X, Y: o.Bounds.B.Y}).Mag()))
  39. dist = math.Min(dist, float64(p.Sub(v.Point2d{X: o.Bounds.B.X, Y: o.Bounds.A.Y}).Mag()))
  40. return dist
  41. }
  42. func obstacleFromValues(x, y, w, h float64, hp int) (o Obstacle) {
  43. return Obstacle{
  44. Bounds: v.AABB2d{
  45. A: v.Point2d{X: x, Y: y},
  46. B: v.Point2d{X: x + w, Y: y + h},
  47. },
  48. Hp: hp,
  49. }
  50. }
  51. // GenerateObstacles returns a slice of (count) obstacles within a region
  52. // bounded by width, height.
  53. func GenerateObstacles(count int, width, height float64) []Obstacle {
  54. out := []Obstacle{}
  55. // Create obstacles that cover the edges of the world, so we don't need to
  56. // special case collision at the edges
  57. // left wall
  58. out = append(out, obstacleFromValues(0, 5, 5, height-10, 0))
  59. // // right wall
  60. out = append(out, obstacleFromValues(width-5, 5, 5, height-10, 0))
  61. // // top wall
  62. out = append(out, obstacleFromValues(0, height-5, width, 5, 0))
  63. // bottom wall
  64. out = append(out, obstacleFromValues(0, 0, width, 5, 0))
  65. // Now create N random objects somewhere in the world
  66. for i := 0; i < count; i++ {
  67. x := rand.Float64() * (width - (width / 10))
  68. y := rand.Float64() * (height - (height / 10))
  69. w := rand.Float64()*(width/10) + 20
  70. h := rand.Float64()*(height/10) + 20
  71. out = append(
  72. out,
  73. obstacleFromValues(x, y, w, h, 10000))
  74. }
  75. return out
  76. }