I wanted to add a directional force and I realized that as long as we only have shooting in the game you can get the direction of the force by getting the selected unit from the UnitActionSystem singleton. Also you can get the type of force later by getting the selected action so you could add an explosion if the selected action is “Grenade” and use a directional force if it’s “Shoot”.
Here’s the simple code:
void ApplyForceToRagdoll(Transform root)
{
Vector3 forceDirection = (transform.position - UnitActionSystem.Instance.GetSelectedUnit().transform.position).normalized;
foreach (Transform child in root)
{
float randomForceAmount = Random.Range(0,10f);
if(child.TryGetComponent<Rigidbody>(out Rigidbody rb))
{
rb.AddForce(forceDirection * randomForceAmount, ForceMode.Impulse);
}
ApplyForceToRagdoll(child);
}
}
I also wanted the ragdoll to drop it’s weapon so I added a rigidbody to the ragdoll’s weapon and a collider and then added a CharacterJoint to it and joined it to the elbow bone. Then after a delay I destroy the bone and unparent the weapon (which is unnecessary but foolproof) Here’s the code:
IEnumerator Start()
{
// This will make the ragdoll drop it's weapon.
float delay = Random.Range(0f, 2f);
Debug.Log(delay);
yield return new WaitForSeconds(delay);
_weaponTransform.parent = null;
Destroy(_weaponTransform.GetComponent<CharacterJoint>());
}