distance.go 1.3 KB

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