conetwist.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 constraint
  5. import (
  6. "github.com/g3n/engine/math32"
  7. "github.com/g3n/engine/experimental/physics/equation"
  8. )
  9. // ConeTwist constraint.
  10. type ConeTwist struct {
  11. PointToPoint
  12. axisA *math32.Vector3 // Rotation axis, defined locally in bodyA.
  13. axisB *math32.Vector3 // Rotation axis, defined locally in bodyB.
  14. coneEq *equation.Cone
  15. twistEq *equation.Rotational
  16. angle float32
  17. twistAngle float32
  18. }
  19. // NewConeTwist creates and returns a pointer to a new ConeTwist constraint object.
  20. func NewConeTwist(bodyA, bodyB IBody, pivotA, pivotB, axisA, axisB *math32.Vector3, angle, twistAngle, maxForce float32) *ConeTwist {
  21. ctc := new(ConeTwist)
  22. // Default of pivots and axes should be vec3(0)
  23. ctc.initialize(bodyA, bodyB, pivotA, pivotB, maxForce)
  24. ctc.axisA = axisA
  25. ctc.axisB = axisB
  26. ctc.axisA.Normalize()
  27. ctc.axisB.Normalize()
  28. ctc.angle = angle
  29. ctc.twistAngle = twistAngle
  30. ctc.coneEq = equation.NewCone(bodyA, bodyB, ctc.axisA, ctc.axisB, ctc.angle, maxForce)
  31. ctc.twistEq = equation.NewRotational(bodyA, bodyB, maxForce)
  32. ctc.twistEq.SetAxisA(ctc.axisA)
  33. ctc.twistEq.SetAxisB(ctc.axisB)
  34. // Make the cone equation push the bodies toward the cone axis, not outward
  35. ctc.coneEq.SetMaxForce(0)
  36. ctc.coneEq.SetMinForce(-maxForce)
  37. // Make the twist equation add torque toward the initial position
  38. ctc.twistEq.SetMaxForce(0)
  39. ctc.twistEq.SetMinForce(-maxForce)
  40. ctc.AddEquation(ctc.coneEq)
  41. ctc.AddEquation(ctc.twistEq)
  42. return ctc
  43. }
  44. // Update updates the equations with data.
  45. func (ctc *ConeTwist) Update() {
  46. ctc.PointToPoint.Update()
  47. // Update the axes to the cone constraint
  48. worldAxisA := ctc.bodyA.VectorToWorld(ctc.axisA)
  49. worldAxisB := ctc.bodyB.VectorToWorld(ctc.axisB)
  50. ctc.coneEq.SetAxisA(&worldAxisA)
  51. ctc.coneEq.SetAxisB(&worldAxisB)
  52. // Update the world axes in the twist constraint
  53. tA, _ := ctc.axisA.RandomTangents()
  54. worldTA := ctc.bodyA.VectorToWorld(tA)
  55. ctc.twistEq.SetAxisA(&worldTA)
  56. tB, _ := ctc.axisB.RandomTangents()
  57. worldTB := ctc.bodyB.VectorToWorld(tB)
  58. ctc.twistEq.SetAxisB(&worldTB)
  59. ctc.coneEq.SetAngle(ctc.angle)
  60. ctc.twistEq.SetMaxAngle(ctc.twistAngle)
  61. }