To apply force to a ragdoll's body part, follow these steps:
- Follow the Creating a humanoid ragdoll with the ragdoll wizard recipe to have a character with a working ragdoll and the HandleRagdoll.cs script (a script to turn the ragdoll on).
- Create a new C# script and name it RagdollForceApply.cs. In this script's Update() function, we first check whether the player clicks on the left mouse button. Then we create a ray from the mouse cursor position in the camera's direction and we check if we hit a collider that has one of the layers described by the publicLayer Mask ragdollBodyPartsLayer variable. If we manage to hit a collider, we try to get the Rigidbody component from it and store it in our Rigidbody hitBodyPart variable. If we indeed find the rigid body, we call the void ApplyForce() function:
if (Input.GetKeyDown(KeyCode.Mouse0)) { if (Physics.Raycast(Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo, 100f, ragdollBodyPartsLayer)) { hitPodyPart = hitInfo.collider.gameObject .GetComponent<Rigidbody>(); if (hitPodyPart != null) { AddForce(); } } }
- The void ApplyForce() function turns the ragdoll on using the HandleRagdoll script. After that, it applies the force in the camera direction with the public float forceMagnitude strength:
void AddForce() { ragdollHandler.EnableRagdoll(true); force = (hitInfo.point - Camera.main.transform.position).normalized * forceMagnitude; hitPodyPart.AddForce(force, ForceMode.Impulse); }
- We set the reference to the HandleRagdoll script in the Start() function.
- Add the script to the character.
- Make sure the character ragdoll's body parts have the proper Layer set.
- Set the Ragdoll Body Parts Layer mask in the RagdollForceApply in the Inspector to match the layer of the ragdoll's body parts.
- Play the game and click on any given body part of the character to see the effect.