In this lesson, you will learn how to use the SliderJoint2D component to restrict an object's movement to a single linear axis, perfect for building functional drawers or moving platforms.
Understanding the Slider Joint
While a HingeJoint2D allows an object to rotate around a pivot point, the SliderJoint2D forces an object to move strictly along a specific line—like a bead on a wire. This is essential for mechanics that require linear motion, such as a drawer sliding in and out of a desk or an elevator moving between two floors.
Configuring the Joint
To set this up, select the object you want to move (like a drawer) and add the SliderJoint2D component.
- RigidBody2D: Ensure your sliding object has a
Rigidbody2Dcomponent attached. - Connected Body: You can leave this empty to anchor the slider to the world, or assign a parent object (like the desk cabinet) to move the drawer relative to the furniture.
- Angle: This property defines the direction of the slide. If you want a horizontal drawer, keep this at
0. For a vertical elevator, set it to90. - Limits: Enable "Use Limits" to define exactly how far the object can slide. By setting a
Lower AngleandUpper Angle(which actually function as distance limits in the Slider component), you can prevent the drawer from flying out of the cabinet completely.
Controlling Movement
You don’t need to write complex physics code to move these objects. Once the joint is configured, you can simply apply a force to the object’s Rigidbody2D using AddForce, or adjust its position via the Transform. The joint will automatically handle the physics constraints, ensuring the object stays perfectly aligned to your chosen axis regardless of the force applied.
// Example: Applying a small force to push a drawer open
public class DrawerController : MonoBehaviour {
private Rigidbody2D rb;
void Start() => rb = GetComponent<Rigidbody2D>();
public void PushDrawer() {
// The SliderJoint2D keeps the drawer on its track automatically
rb.AddForce(transform.right * 5f, ForceMode2D.Impulse);
}
}
Key Takeaway: The SliderJoint2D acts as a virtual track, locking an object’s physics movement to a single linear axis while allowing you to define precise boundaries for its travel range.