What Is the Purpose of a Motor Joint in Planck.js?
A motor joint in planck.js—a 2D physics engine for JavaScript games and simulations—is used to control the relative motion between two rigid bodies by applying linear and angular forces. Unlike other joints that rigidly constrain movement or simulate physical connections like hinges, a motor joint drives a body toward a target position and orientation relative to another body. This article explores how motor joints work, their primary use cases, and how they differ from other joint types in the engine.
How a Motor Joint Works
The motor joint attempts to match a specific target offset and target angle between two connected bodies. It computes the necessary linear force and torque required to eliminate the gap between the current state and the desired state.
Key properties that define its behavior include:
- Linear Offset: The desired relative position of body B relative to body A.
- Angular Offset: The desired relative rotation between the two bodies.
- Maximum Force: The upper limit of linear force the joint can apply to reach the target position.
- Maximum Torque: The upper limit of rotational force the joint can exert to reach the target angle.
- Correction Factor: A multiplier (usually between 0 and 1) that determines how aggressively the joint corrects deviations.
Key Use Cases
Motor joints are highly versatile because they do not completely lock bodies together, allowing for smooth, force-limited corrections. Common applications include:
- Character Movement: Driving a character’s physics body toward a cursor position or moving platform while still allowing the character to be pushed back by heavy obstacles.
- Kinematic-like Behavior with Forces: Moving dynamic objects along a specific path or to a specific spot without overriding the physics solver, ensuring they still collide naturally with other objects.
- Regulating Relative Rotation: Keeping an object upright or tilted at a specific angle relative to another moving object, such as a vehicle chassis.
Motor Joint vs. Other Joints
While joints like the Revolute Joint or Prismatic Joint have built-in “motors” to spin a wheel or slide a piston, the Motor Joint itself is an independent joint type designed entirely around tracking a relative transform.
| Joint Type | Primary Function | Control Mechanism |
|---|---|---|
| Motor Joint | Drives a body to a relative position and angle | Linear and angular offsets with maximum force limits |
| Revolute Joint | Constraints bodies to a shared pivot point | Optional angular motor to control rotational speed |
| Prismatic Joint | Constraints movement along a single linear axis | Optional linear motor to control translation speed |
By using a motor joint, developers gain fine-grained control over object positioning through forces, maintaining realistic physics interactions without sacrificing precise movement controls.