broadphase.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 physics
  6. import (
  7. "github.com/g3n/engine/experimental/physics/object"
  8. )
  9. // CollisionPair is a pair of bodies that may be colliding.
  10. type CollisionPair struct {
  11. BodyA *object.Body
  12. BodyB *object.Body
  13. }
  14. // Broadphase is the base class for broadphase implementations.
  15. type Broadphase struct{}
  16. // NewBroadphase creates and returns a pointer to a new Broadphase.
  17. func NewBroadphase() *Broadphase {
  18. b := new(Broadphase)
  19. return b
  20. }
  21. // FindCollisionPairs (naive implementation)
  22. func (b *Broadphase) FindCollisionPairs(objects []*object.Body) []CollisionPair {
  23. pairs := make([]CollisionPair, 0)
  24. for iA, bodyA := range objects {
  25. for _, bodyB := range objects[iA+1:] {
  26. if b.NeedTest(bodyA, bodyB) {
  27. BBa := bodyA.BoundingBox()
  28. BBb := bodyB.BoundingBox()
  29. if BBa.IsIntersectionBox(&BBb) {
  30. pairs = append(pairs, CollisionPair{bodyA, bodyB})
  31. }
  32. }
  33. }
  34. }
  35. return pairs
  36. }
  37. func (b *Broadphase) NeedTest(bodyA, bodyB *object.Body) bool {
  38. if !bodyA.CollidableWith(bodyB) || (bodyA.Sleeping() && bodyB.Sleeping()) {
  39. return false
  40. }
  41. return true
  42. }