broadphase.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package collision implements collision related algorithms and data structures.
  5. package collision
  6. import (
  7. "github.com/g3n/engine/physics/object"
  8. )
  9. // Broadphase is the base class for broadphase implementations.
  10. type Broadphase struct {}
  11. type Pair struct {
  12. BodyA *object.Body
  13. BodyB *object.Body
  14. }
  15. // NewBroadphase creates and returns a pointer to a new Broadphase.
  16. func NewBroadphase() *Broadphase {
  17. b := new(Broadphase)
  18. return b
  19. }
  20. // FindCollisionPairs (naive implementation)
  21. func (b *Broadphase) FindCollisionPairs(objects []*object.Body) []Pair {
  22. pairs := make([]Pair,0)
  23. for iA, bodyA := range objects {
  24. for _, bodyB := range objects[iA+1:] {
  25. if b.NeedTest(bodyA, bodyB) {
  26. BBa := bodyA.BoundingBox()
  27. BBb := bodyB.BoundingBox()
  28. if BBa.IsIntersectionBox(&BBb) {
  29. pairs = append(pairs, Pair{bodyA, bodyB})
  30. }
  31. }
  32. }
  33. }
  34. return pairs
  35. }
  36. func (b *Broadphase) NeedTest(bodyA, bodyB *object.Body) bool {
  37. if !bodyA.CollidableWith(bodyB) || (bodyA.Sleeping() && bodyB.Sleeping()) {
  38. return false
  39. }
  40. return true
  41. }