Creating p2 Constraint Programatically

I am having problems creating p2 physics constraint programatically.

I am using the p2 physics library with PlayCanvas integration.

I am creating a p2RevoluteConstraint programmatically and assigning the 2 entities like so:

var rc = freeBubble.script.create('p2RevoluteConstraint');
rc.entityA = playerBubble;
rc.entityB = freeBubble;

But I get an error on line 1347 of p2-integration.js:

Cannot read property 'off' of null

So I changed the event code to:

if(prev) {
    prev.off('p2:newBody');
}

But now the bubbles collide with no errors but the bubble that should be attached just gets pushed away (unaffected by new constraint), which you can see if you play the project, press left click to spawn a bubble, and collide with it using WASD.

I am even logging the 2 entities that collided to console and it states that the entityA and entityB are assigned, but like I said the entities act as if the constraint isn’t even there.

How do I properly create a new constraint in code?

Project overview: https://playcanvas.com/project/722463/overview/bubs

I be honest that I have no idea what a revolute constraint is :sweat_smile:

From the looks of the code, the constraint is created on postInitialise of the script p2RevoluteConstraint. This gets called as part of the script.create function so setting entityA and B on the next line is too late.

They should be passed as attributes when the script is created:

    var rc = freeBubble.script.create('p2RevoluteConstraint', {
        attributes: {
            entityA: playerBubble,
            entityB: freeBubble,
            stiffness: 100 
        }
    });

Which gives the following result which I have no idea if expected?

Code: https://playcanvas.com/editor/code/722788?tabs=35904011&line=51

2 Likes

I swear I tried that before but it didn’t work. Oh well, thanks. I wonder if I change the entities AFTER the fact what kind of effect that will have? Probably a future post from me.
Anyways thank you.