distance.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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/experimental/physics/equation"
  7. )
  8. // Distance is a distance constraint.
  9. // Constrains two bodies to be at a constant distance from each others center of mass.
  10. type Distance struct {
  11. Constraint
  12. distance float32 // Distance
  13. equation *equation.Contact
  14. }
  15. // NewDistance creates and returns a pointer to a new Distance constraint object.
  16. func NewDistance(bodyA, bodyB IBody, distance, maxForce float32) *Distance {
  17. dc := new(Distance)
  18. dc.initialize(bodyA, bodyB, true, true)
  19. // Default distance should be: bodyA.position.distanceTo(bodyB.position)
  20. // Default maxForce should be: 1e6
  21. dc.distance = distance
  22. dc.equation = equation.NewContact(bodyA, bodyB, -maxForce, maxForce) // Make it bidirectional
  23. dc.AddEquation(dc.equation)
  24. return dc
  25. }
  26. // Update updates the equation with data.
  27. func (dc *Distance) Update() {
  28. halfDist := dc.distance * 0.5
  29. posA := dc.bodyA.Position()
  30. posB := dc.bodyB.Position()
  31. normal := posB.Sub(&posA)
  32. normal.Normalize()
  33. dc.equation.SetRA(normal.Clone().MultiplyScalar(halfDist))
  34. dc.equation.SetRB(normal.Clone().MultiplyScalar(-halfDist))
  35. }