Add velocity / forces from object to instantiated ragdoll

Hi All!

I want some NPC’s to turn into ragdolls when colliding with the player. For some reason I can’t seem to give the instantiated ragdoll the same velocity / force, as the NPC it instantiated from, and it just stops and slides to the ground… Did I script it wrong? Or did I take a whole wrong aproach to giving the Ragdoll velocity when instantiated?

    function OnCollisionEnter(collision : Collision)
    {
        if(collision.gameObject.tag == "Player"){
     	ragdoll = Instantiate(ragdoll, transform.position, transform.rotation);

     	colliders = ragdoll.GetComponentsInChildren(Collider);
       	for (var col : Collider in colliders)
                {
      	        Physics.IgnoreCollision(col, collider);
            	}
    
       rigidbodies = ragdoll.GetComponentsInChildren(Rigidbody);
           	for (var child : Rigidbody in rigidbodies) 
                {
        	    child.rigidbody.velocity = rigidbody.velocity;
        	    child.angularVelocity = rigidbody.angularVelocity;
    	        //child.rigidbody.AddForce (Vector3.up * 1000);
                }	
    	Destroy(gameObject);
    	}
    }

the rigidboy.AddForce at the end is there for test purposes, and works in the current setup. Setting the child’s velocities doesn’t seem to work at all though… If been searching for a while now, since I’m guessing it’s a common problem, but I can’t seem to find anything usefull on the subject…

Thanks in advance!! I’ve been struggling with this for days, any help apriciated!

That’s an interesting question, thus I decided to test this script. It worked fine, but with some peculiarities: when the NPC collides with a static or heavy thing, its velocity falls to almost zero - and such small velocity is transfered to the ragdoll, what makes it just fall down; on the other hand, if it collides with some light object, its rigidbody.velocity doesn’t change too much, and the ragdoll parts continue moving as the original object.

I tried a simple trick: I stored the rigidbody velocity and angularVelocity in two variables during FixedUpdate, and copied these values to the ragdoll parts in OnCollisionEnter, and it worked fine! It seems that FixedUpdate occurs before the collision detection, thus when OnCollisionEnter happens the old velocity is safely stored in those variables.

That’s the trick:

var lastVel: Vector3; // save the rigidbody velocities in
var lastAngVel: Vector3; // these variables

function FixedUpdate(){
  lastVel = rigidbody.velocity;
  lastAngVel = rigidbody.angularVelocity;
}

function OnCollisionEnter(collision : Collision)
{
    ...
    for (var child : Rigidbody in rigidbodies) 
    {
        child.velocity = lastVel; // use the saved velocities
        child.angularVelocity = lastAngVel;
    }   
    ...