#

API Docs for: 0.6.1
Show: Inherited Protected Private Deprecated

# File: src/constraints/DistanceConstraint.js

    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);
    };