Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent relative rotation in Matter.js constraint

I'm using Matter.js and I want two rectangles with a constraint to make them act if they where a single rigid object.

I am basically setting stiffness to 1, so the contraint acts like a rigid bar instead of a spring. Also to prevent the object from rotating, I'm setting the intertia to Infinity.

  // a 20x20 square with 0 friction and infinite inertia
  let objectA = Bodies.rectangle(0, 0, 20, 20, {
      frictionAir: 0,
      inertia: 'Infinity'
  });
  let objectB = Bodies.rectangle(30, 0, 20, 20, {
      frictionAir: 0,
      inertia: 'Infinity'
  });

  let constraint = Constraint.create({
      bodyA: objectB,
      bodyB: objectB,
      length: 30,
      stiffness: 1);

This indeed creates 2 objects with a fixed distance and they do not rotate (both squares always have the same absolute orientation)

enter image description here

However the objects can rotate between them, the constrain acts as a linear constraint but not as an angular constraint. This picture shows how the distance between objects is kept, how the absolute orientation of the objects has not changed but how the objects rotate around each other.

How can I get rid of this rotation and have the two objects act if they were a single object?

enter image description here


1 Answers

I use a different approach: building a Body from parts instead of using constraints. The result is a single rigid object. Matter handles the parts still separately, so you can e.g. drop a ball in the cart created with the code below.

let cart = bodyWithParts(200, 150, { isStatic: true, friction: 0.0 });

function bodyWithParts(x, y, options) {
  options = options || {}
  let w = 4;
  options.parts = [];
  options.parts.push(Matter.Bodies.rectangle(w, 20, 5, 20));
  options.parts.push(Matter.Bodies.rectangle(40 - w, 20, 5, 20));
  options.parts.push(Matter.Bodies.rectangle(20, 40 - w, 50, 5))
  let body = Matter.Body.create(options)
  Matter.Body.setPosition(body, { x: x, y: y });
  return body;
}
like image 52
Byron Star Avatar answered Nov 20 '25 18:11

Byron Star



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!