P2/Phaser Revolute Constraint Made Simple

Revolute constraint is a way for two physics objects in the P2 physics system to interact with one another. This is a revolving type of constraint that can be used to create a hinge or a joint. The two bodies end up having a pivot point between them.

P2 is a realistic and complex JavaScript engine. It is one of the main physics engines used by Phaser.js, a popular HTML5 game library. You can see an example of Revolute Constraint on the Phaser website. You can see in this example that the arrow and the bar spin around a pivot point between the two of them.

Another example of the revolute constraint along with other types of constraints offered by the P2.js physics engine can be found here.

If you are looking to use P2 physics inside of your Phaser game, it can be more benegital to look at the P2 documentation directly rather than looking at the Phaser documentation. The P2 documentation goes into more depth than does the Phaser documentation. There is little reason for Phaser to recreate all the documentation that already existing for the P2 library.

A much more impressive example of the revolute constraint is P2's ragdoll. You see that each body part is held together by the constraints, and is able to rotate around the joint location. This makes this type of constraint great for joining body parts. The maximum angle of each constraint can also be set, making the joints similar to a physical body.

In Phaser the code for creating a revolute constraint between two bodies (lets say an arm and a hand) looks like this:

let joint = game.physics.p2.createRevoluteConstraint(arm, [arm.width/2,0], hand, [-hand.width/2,0]);

joint.setLimits(-Math.PI/4, Math.PI/4);

A lot of this should already be familiar to you. 'arm' and 'hand' are sprites/bodies. [arm.width/2,0] is an array holding the position of the constraint relative to the 'arm' sprite. 'arm.width/2' is the x offset value and '0' is the y offset value. In this case we tell Phaser/P2 to have the revolution point for 'arm' be at the center of the 'arm' body plus half it's width to the right. The 'hand' offset is offset half the hand's width to the left (negative).

The next line sets the revolution limits for this constraint. Without any limits the two bodies can spin around each other in infinite circles. This line sets a limit (in radians) of how far the two bodies can spin. If they reach these angle limits they stop spinning. You can see this in the above ragdoll example where the body joints to not spin a full circle relative to one another.

To gain a further understanding of revolute constraints see the P2.js documentation