How to do it...

To apply force to a ragdoll's body part, follow these steps:

  1. 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).
  2. 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(); 
              } 
          } 
      }     
  1. 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); 
      } 
  1. We set the reference to the HandleRagdoll script in the Start() function.
  2. Add the script to the character.
  3. Make sure the character ragdoll's body parts have the proper Layer set.
  4. Set the Ragdoll Body Parts Layer mask in the RagdollForceApply in the Inspector to match the layer of the ragdoll's body parts.
  5. Play the game and click on any given body part of the character to see the effect.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.239.118