How to Get Joints Connected to a Planck.js Body
This article provides a quick overview of how to access and iterate
through the list of joints attached to a specific rigid body in
planck.js, the 2D JavaScript physics engine based on Box2D.
You will learn about the built-in methods available on the
Body object, see a practical code example, and understand
how to safely manipulate or inspect connected joints during your
simulation.
Accessing Connected Joints via the Joint Edge List
In planck.js, joints are not stored as a simple, flat
array directly inside a Body object. Instead, the engine
uses a linked list structure called a Joint Edge
(JointEdge) list to connect bodies and joints
efficiently.
To retrieve the joints attached to a specific body, you must traverse this list starting from the body’s initial joint edge.
The getJointList()
Method
The Body prototype provides a method called
getJointList(). This method returns the first
JointEdge object connected to that body, or
null if the body has no attached joints.
Each JointEdge object contains three essential
properties:
joint: The actualJointobject (e.g.,RevoluteJoint,DistanceJoint).other: The otherBodyconnected to this joint.next: A pointer to the nextJointEdgein the linked list, ornullif it is the end of the list.
Code Example: Iterating Through a Body’s Joints
To inspect or manipulate all joints connected to a body, you can use
a while loop to traverse the linked list.
// Assume 'myBody' is a planck.Body instance already added to your world
let edge = myBody.getJointList();
while (edge !== null) {
// Access the current joint
let joint = edge.joint;
// Access the other body connected via this joint
let connectedBody = edge.other;
console.log(`Joint Type: ${joint.getType()}, Connected to Body:`, connectedBody);
// Move to the next joint edge in the linked list
edge = edge.next;
}Important Considerations
- Do Not Modify the List Mid-Iteration: If you plan
to destroy joints while looping through the list, destroying a joint
immediately modifies the linked list pointers (
edge.next). To avoid breaking your loop or causing null-pointer exceptions, always store a reference to the next edge (let nextEdge = edge.next) before destroying the current joint. - Bi-directional Connection: Because joints connect
two bodies, the joint will appear in the joint list of both connected
bodies. The
edge.otherproperty is highly convenient because it automatically points to the opposite body relative to the one you calledgetJointList()on.