Make character controller push rigidbodies

how do u make a character controller push rigidbodies when colliding?

I know this is an old topic, but I wanted to share a solution that helped me:

    // Your character controller
    public CharacterController Controller;

    public float pushPower = 0.002f;

    // Define Your collision masks for raycast
    public LayersMask RaycastLayers = new LayersMask(1 << 3);

    float coll_radius = 40f;
    float coll_distance = 45f;

    public override void OnUpdate()
    {
        if (Controller == null)
            return;

        Vector3 velocity = Controller.Velocity;

        if (velocity.LengthSquared < 0.01f)
            return;

        Vector3 direction = velocity.Normalized;

        // DebugDraw Your SphereCast to see it
        DebugDraw.DrawSphere(new BoundingSphere(Actor.Position, coll_radius), Color.WhiteSmoke);

        if (Physics.SphereCast(Actor.Position, coll_radius, direction, out RayCastHit hit, coll_distance, RaycastLayers))
        {
            RigidBody rb = hit.Collider?.AttachedRigidBody;

            // Draw debug hit point
            DebugDraw.DrawSphere(new BoundingSphere(hit.Point, 5), Color.Orange);

            if (rb != null && !rb.IsKinematic)
            {
                Vector3 pushDir = new Vector3(direction.X, 0, direction.Z);
                Vector3 collPoint = hit.Point;

                rb.AddForceAtPosition(pushDir * pushPower, collPoint, ForceMode.Impulse);
            }
        }
    }

With the hierarchy of the object:
-Rigidbody (not kinematic with a mass value)
—Collider/s
—Mesh

1 Like