conetwist.go 2.3 KB

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