fieldkit
Version:
Basic building blocks for computational design projects. Written in CoffeeScript for browser and server environments.
102 lines (70 loc) • 2.35 kB
JavaScript
// Generated by CoffeeScript 1.6.3
(function() {
var Attractor, Behaviour, Force, Vec2, Vec3, physics, vector,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
vector = require('../math/vector');
Vec2 = vector.Vec2;
Vec3 = vector.Vec3;
physics = require('./physics');
Behaviour = physics.Behaviour;
/*
A constant force along a vector e.g. Gravity.
Works in 2D + 3D.
*/
Force = (function(_super) {
var force;
__extends(Force, _super);
force = null;
function Force(direction, weight) {
this.direction = direction;
this.weight = weight != null ? weight : 1;
}
Force.prototype.prepare = function() {
return force = this.direction.normalizeTo(this.weight);
};
Force.prototype.apply = function(particle) {
return particle.position.add(force);
};
Force.prototype.toString = function() {
return "Force(" + force + ")";
};
return Force;
})(Behaviour);
/*
Attracts each particle within range to a target point.
Works in 2D + 3D.
*/
Attractor = (function() {
var rangeSq, tmp;
tmp = null;
rangeSq = 0;
function Attractor(target, range, weight) {
this.target = target;
this.range = range;
this.weight = weight != null ? weight : 1;
tmp = this.target.clone();
}
Attractor.prototype.prepare = function() {
return rangeSq = this.range * this.range;
};
Attractor.prototype.apply = function(particle) {
var dist, distSq;
tmp.set(this.target).sub(particle.position);
distSq = tmp.lengthSquared();
if (distSq > 0 && distSq < rangeSq) {
dist = Math.sqrt(distSq);
tmp.scale((1 / dist) * (1 - dist / this.range) * this.weight);
return particle.force.add(tmp);
}
};
Attractor.prototype.toString = function() {
return "Attractor(" + this.target + ", " + this.range + ", " + this.weight + ")";
};
return Attractor;
})();
module.exports = {
Force: Force,
Attractor: Attractor
};
}).call(this);