forked from schteppe/cannon.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistanceConstraint.js
56 lines (47 loc) · 1.52 KB
/
DistanceConstraint.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module.exports = DistanceConstraint;
var Constraint = require('./Constraint');
var ContactEquation = require('../equations/ContactEquation');
/**
* Constrains two bodies to be at a constant distance from each others center of mass.
* @class DistanceConstraint
* @constructor
* @author schteppe
* @param {Body} bodyA
* @param {Body} bodyB
* @param {Number} [distance] The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
* @param {Number} [maxForce=1e6]
* @extends Constraint
*/
function DistanceConstraint(bodyA,bodyB,distance,maxForce){
Constraint.call(this,bodyA,bodyB);
if(typeof(distance)==="undefined") {
distance = bodyA.position.distanceTo(bodyB.position);
}
if(typeof(maxForce)==="undefined") {
maxForce = 1e6;
}
/**
* @property {number} distance
*/
this.distance = distance;
/**
* @property {ContactEquation} distanceEquation
*/
var eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
this.equations.push(eq);
// Make it bidirectional
eq.minForce = -maxForce;
eq.maxForce = maxForce;
}
DistanceConstraint.prototype = new Constraint();
DistanceConstraint.prototype.update = function(){
var bodyA = this.bodyA;
var bodyB = this.bodyB;
var eq = this.distanceEquation;
var halfDist = this.distance * 0.5;
var normal = eq.ni;
bodyB.position.vsub(bodyA.position, normal);
normal.normalize();
normal.mult(halfDist, eq.ri);
normal.mult(-halfDist, eq.rj);
};