In this lesson, you will learn how to configure a Hinge Joint component to create doors that swing naturally using Unity’s physics engine.
Understanding the Hinge Joint
A Hinge Joint acts as a physical pivot point, similar to a real-world door hinge. Instead of manually animating a door’s rotation, you use the physics engine to calculate how the door swings when interacted with. To set this up, your door GameObject must have a Rigidbody component attached.
When you add the Hinge Joint component, you define an Anchor and an Axis. The Anchor is the specific spot on the door where the "hinge" is placed, and the Axis defines the line around which the door rotates—usually the vertical (Y) axis for a standard swinging door.
Configuring for Interaction
To make a door feel realistic, you need to restrict its movement so it doesn't spin 360 degrees like a fan. Use the Limits property in the Hinge Joint inspector:
- Enable Limits: Check the "Use Limits" box.
- Min/Max: Set these to define the arc of the swing (e.g., -90 to 90 degrees).
- Spring: You can enable the "Spring" property if you want the door to automatically return to a closed position after it is pushed.
Since we have already covered Physics-Based Character Pushing and Impulse Forces, you can trigger the door's movement by applying a force at the handle when your player interacts with it:
// Example: Applying a force to swing the door when the player pushes it
void PushDoor(Vector3 pushDirection, float force)
{
Rigidbody doorRb = GetComponent<Rigidbody>();
// Apply force at the point of interaction (the door handle)
doorRb.AddForceAtPosition(pushDirection * force, transform.position, ForceMode.Impulse);
}
By combining a Rigidbody with proper Hinge Joint limits, the door will respect physical constraints, collide properly with the environment, and swing only as far as you permit. This creates a tactile, responsive world that reacts to the player's presence rather than relying on pre-baked animations.
Key Takeaway: Hinge joints leverage the Rigidbody and axis constraints to simulate realistic door movement, turning interaction into a natural extension of your physics-based gameplay.