Create DistanceJoint from collision

I am trying to create a DistanceJoint between two colliding particles using Box2d and p5.js. I am essentially trying to merge these two codes from the p5.js Nature of Code:

NOC 5.6

NOC 5.9

Here is my code:

The problem with it is that even though I am running world.CreateJoint(djd); it does not actually create a joint. There is no error message for why.

Can someone tell me why the code below isn't working? Don't say that the the joint should be under EndContact. I already tried that.

// ContactListener to listen for collisions!

function CustomListener() {

// Collision event functions! this.BeginContact = function(contact) { // Get both fixtures var f1 = contact.GetFixtureA(); var f2 = contact.GetFixtureB(); // Get both bodies var b1 = f1.GetBody(); var b2 = f2.GetBody(); //console.log(b1);

// Get our objects that reference these bodies
var o1 = b1.GetUserData();
var o2 = b2.GetUserData();

if (o1 instanceof Particle && o2 instanceof Particle) {

  var djd = new box2d.b2DistanceJointDef();

  djd.length = scaleToWorld(32);

  // CMO -- the problem seems to start here
  djd.bodyA = b1;
  djd.bodyB = b2;
  djd.frequencyHz = 3;  // Try a value less than 5 (0 for no elasticity)
  djd.dampingRatio = 0.1; // Ranges between 0 and 1 (1 for no springiness)

  var dj = world.CreateJoint(djd);
  print(dj); // returns null

  // successfully changes the color of particle A & B


// Objects stop touching each other this.EndContact = function(contact) { };

this.PreSolve = function(contact,manifold) { };

this.PostSolve = function(contact,manifold) { }; }

Sign In or Register to comment.