cone.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 physics implements a basic physics engine.
  5. package equation
  6. import (
  7. "github.com/g3n/engine/math32"
  8. )
  9. // Cone is a cone constraint equation.
  10. // Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
  11. type Cone struct {
  12. Equation
  13. axisA *math32.Vector3 // Local axis in A
  14. axisB *math32.Vector3 // Local axis in B
  15. angle float32 // The "cone angle" to keep
  16. }
  17. // NewCone creates and returns a pointer to a new Cone equation object.
  18. func NewCone(bodyA, bodyB IBody, axisA, axisB *math32.Vector3, angle, maxForce float32) *Cone {
  19. ce := new(Cone)
  20. ce.axisA = axisA // new Vec3(1, 0, 0)
  21. ce.axisB = axisB // new Vec3(0, 1, 0)
  22. ce.angle = angle // 0
  23. ce.Equation.initialize(bodyA, bodyB, -maxForce, maxForce)
  24. return ce
  25. }
  26. // SetAxisA sets the axis of body A.
  27. func (ce *Cone) SetAxisA(axisA *math32.Vector3) {
  28. ce.axisA = axisA
  29. }
  30. // AxisA returns the axis of body A.
  31. func (ce *Cone) AxisA() math32.Vector3 {
  32. return *ce.axisA
  33. }
  34. // SetAxisB sets the axis of body B.
  35. func (ce *Cone) SetAxisB(axisB *math32.Vector3) {
  36. ce.axisB = axisB
  37. }
  38. // AxisB returns the axis of body B.
  39. func (ce *Cone) AxisB() math32.Vector3 {
  40. return *ce.axisB
  41. }
  42. // SetAngle sets the cone angle.
  43. func (ce *Cone) SetAngle(angle float32) {
  44. ce.angle = angle
  45. }
  46. // MaxAngle returns the cone angle.
  47. func (ce *Cone) Angle() float32 {
  48. return ce.angle
  49. }
  50. // ComputeB
  51. func (ce *Cone) ComputeB(h float32) float32 {
  52. // The angle between two vector is:
  53. // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b
  54. // g = a * b
  55. // gdot = (b x a) * wi + (a x b) * wj
  56. // G = [0 bxa 0 axb]
  57. // W = [vi wi vj wj]
  58. ce.jeA.SetRotational(math32.NewVec3().CrossVectors(ce.axisB, ce.axisA))
  59. ce.jeB.SetRotational(math32.NewVec3().CrossVectors(ce.axisA, ce.axisB))
  60. g := math32.Cos(ce.angle) - ce.axisA.Dot(ce.axisB)
  61. GW := ce.ComputeGW()
  62. GiMf := ce.ComputeGiMf()
  63. return -g*ce.a - GW*ce.b - h*GiMf
  64. }