0
0
Fork 0
mirror of https://github.com/liabru/matter-js.git synced 2024-11-30 10:20:52 -05:00
liabru-matter-js/src/constraint/MouseConstraint.js
2014-04-01 13:45:15 +01:00

87 lines
No EOL
2.6 KiB
JavaScript

/**
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class MouseConstraint
*/
var MouseConstraint = {};
(function() {
/**
* Description
* @method create
* @param {engine} engine
* @param {} options
* @return {MouseConstraint} A new MouseConstraint
*/
MouseConstraint.create = function(engine, options) {
var mouse = engine.input.mouse;
var constraint = Constraint.create({
pointA: mouse.position,
pointB: { x: 0, y: 0 },
length: 0.01,
stiffness: 0.1,
angularStiffness: 1,
render: {
strokeStyle: '#90EE90',
lineWidth: 3
}
});
var defaults = {
type: 'mouseConstraint',
mouse: mouse,
dragBody: null,
dragPoint: null,
constraint: constraint
};
var mouseConstraint = Common.extend(defaults, options);
Events.on(engine, 'tick', function(event) {
var allBodies = Composite.allBodies(engine.world);
MouseConstraint.update(mouseConstraint, allBodies);
});
return mouseConstraint;
};
/**
* Description
* @method update
* @param {MouseConstraint} mouseConstraint
* @param {body[]} bodies
*/
MouseConstraint.update = function(mouseConstraint, bodies) {
var mouse = mouseConstraint.mouse,
constraint = mouseConstraint.constraint;
if (mouse.button === 0) {
if (!constraint.bodyB) {
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
if (Bounds.contains(body.bounds, mouse.position)
&& Vertices.contains(body.vertices, mouse.position)) {
constraint.pointA = mouse.position;
constraint.bodyB = body;
constraint.pointB = { x: mouse.position.x - body.position.x, y: mouse.position.y - body.position.y };
constraint.angleB = body.angle;
Sleeping.set(body, false);
}
}
}
} else {
constraint.bodyB = null;
constraint.pointB = null;
}
if (constraint.bodyB) {
Sleeping.set(constraint.bodyB, false);
constraint.pointA = mouse.position;
}
};
})();