sphere.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 shape
  5. import "github.com/g3n/engine/math32"
  6. // Sphere is an analytical collision sphere.
  7. type Sphere struct {
  8. radius float32
  9. }
  10. // NewSphere creates and returns a pointer to a new analytical collision sphere.
  11. func NewSphere(radius float32) *Sphere {
  12. s := new(Sphere)
  13. s.radius = radius
  14. return s
  15. }
  16. // SetRadius sets the radius of the analytical collision sphere.
  17. func (s *Sphere) SetRadius(radius float32) {
  18. s.radius = radius
  19. }
  20. // Radius returns the radius of the analytical collision sphere.
  21. func (s *Sphere) Radius() float32 {
  22. return s.radius
  23. }
  24. // IShape =============================================================
  25. // BoundingBox computes and returns the bounding box of the analytical collision sphere.
  26. func (s *Sphere) BoundingBox() math32.Box3 {
  27. return math32.Box3{math32.Vector3{-s.radius, -s.radius, -s.radius}, math32.Vector3{s.radius, s.radius, s.radius}}
  28. }
  29. // BoundingSphere computes and returns the bounding sphere of the analytical collision sphere.
  30. func (s *Sphere) BoundingSphere() math32.Sphere {
  31. return *math32.NewSphere(math32.NewVec3(), s.radius)
  32. }
  33. // Area computes and returns the surface area of the analytical collision sphere.
  34. func (s *Sphere) Area() float32 {
  35. return 4 * math32.Pi * s.radius * s.radius
  36. }
  37. // Volume computes and returns the volume of the analytical collision sphere.
  38. func (s *Sphere) Volume() float32 {
  39. return (4 / 3) * math32.Pi * s.radius * s.radius * s.radius
  40. }
  41. // RotationalInertia computes and returns the rotational inertia of the analytical collision sphere.
  42. func (s *Sphere) RotationalInertia(mass float32) math32.Matrix3 {
  43. v := (2 / 5) * mass * s.radius * s.radius
  44. return *math32.NewMatrix3().Set(
  45. v, 0, 0,
  46. 0, v, 0,
  47. 0, 0, v,
  48. )
  49. }
  50. // ProjectOntoAxis computes and returns the minimum and maximum distances of the analytical collision sphere projected onto the specified local axis.
  51. func (s *Sphere) ProjectOntoAxis(localAxis *math32.Vector3) (float32, float32) {
  52. return -s.radius, s.radius
  53. }