Character Controller How to Add Ability to Push Rigidbodies in Unity
In this tutorial, we'll enhance the Unity FPS Controller script to enable the character to push rigidbodies within the scene (the script below should work with any controller, as long as it has an attached CharacterController component). This script can add a realistic touch to your game by allowing players to interact with objects and dynamic environments.
Step 1: Create a New Script
- Create a new C# script in your Unity project. You can name it something like "CharacterPushController".
Step 2: Copy the Provided Script
- Copy the code below into the newly created script. You can adjust the 'pushPower' variable to control the strength of the push. Additionally, you may want to customize the conditions for applying the push force based on your game's logic.
CharacterPushController.cs
using UnityEngine;
public class CharacterPushController : MonoBehaviour
{
// Adjust this variable to control the strength of the push
public float pushPower = 2.0f;
void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
// No rigidbody or kinematic rigidbody
if (body == null || body.isKinematic)
{
return;
}
// Avoid pushing objects below the character
if (hit.moveDirection.y < -0.3)
{
return;
}
// Calculate push direction from move direction,
// pushing only to the sides, not up and down
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
// Apply the push
body.velocity = pushDir * pushPower;
}
}
Step 3: Attach the Script
- Attach the "CharacterPushController" script to the GameObject with the CharacterController component.
Step 4: Test
- Play the scene and test the character controller's ability to push rigidbodies with the help of the newly created script.
Step 5: Adjust
- Adjust the 'pushPower' to achieve the desired behavior in your game.