Mecanim to Ragdoll in Unity 3d

Sharing is caring:

Create a Ragdoll with Mecanim Capabilities

In this three part Unity 3d tutorial we’ll be showing you how to setup a character as a ragdoll, apply animations using Mecanim, and turn him into a ragdoll once we shoot a projectile at him. This is part one of the series that will cover how to properly setup a ragdoll with our rigged character. For this video we’ll be using a free asset off the Unity 3d asset store that contains the rigged character and animations needed.

Applying Mecanim Animations

In this second video of our Mecanim to Ragdoll tutorial series we’ll be adding animations to our character using Mecanim. This video will not be going in depth with how to use Mecanim but will teach you the very basics of setting up a character to use animations with Mecanim. The packaged (link below) asset comes with a plethora of animations that we can use.

For this video we’ll be going over a few of them to include an idle animation and a running/jumping type of animation. We’ll show you the basics of trimming an animation clip and how to seamlessly loop an animation clip to play over and over again. We’ll briefly go over the animator controller window and some of the settings that we’ll be changing.

Activating Ragdoll on Collision

In this final video we’ll wrap things up by showing you how to apply scripts to our character to turn him into a ragdoll once we shoot him with a cannonball. We’ll be using three different scripts; one for the instantiation, one for the collision to be registered, and one for the ragdoll “activation”. You’ll need to create a prefab of the cannonball that has a rigidbody attached to it.

This will register a collision once it comes in contact with any of the colliders attached to our rigidbody bones. The cannonball will have a script that contains a “OnCollisionEnter” script that will use a “Send Message” to call a function from our “ragdollCharacter” script.

The character will have the ragdollCharacter script that will “collect” all the rigidbody bones and disable the “isKinematic” feature. We’ll also be disabling the Animator Controller on our character so that the animations will stop playing and he will turn into a ragdoll. Scripts and link to Asset can be found below:

 

Assets Used

Raw Mocap data for Mecanim

 

Javascript Files

cannonballHit.js (apply to the cannonball prefab)

 

 


#pragma strict

function OnCollisionEnter (col : Collision) {

if(col.gameObject.tag == "ragdollBones") {

gameObject.Find("Ragdoll").SendMessage("killRagdoll");

}
Destroy(gameObject, 3);

}

 

 

CannonShoot.js (apply to empty gameObject to instantiate cannonball prefab)


#pragma strict

var cannonball : GameObject; //Prefab of your cannonball or projectile
var rateOfFire : float = 0.5; //Determines the rate of fire
internal var fireDelay : float; //Determines delay between when you can shoot
var speed : float = 20; //Determines the speed at which you can shoot

function Update () {

if (Input.GetButton("Fire1") && Time.time > fireDelay) {  //Ensures that player has pressed the "Fire1" button and all other parameters have been met before firing

fireDelay = Time.time + rateOfFire;
var clone : GameObject = Instantiate (cannonball, transform.position, transform.rotation); //Clones prefab "cannonball"
clone.rigidbody.velocity = transform.TransformDirection(Vector3 (0,0,speed));//Shoots "cannonball" in the Z-axis based off "speed" variable
Physics.IgnoreCollision(clone.collider, transform.root.collider);

}

}

 

 

RagdollController.js (apply to our character)


#pragma strict

var boneRig : Component[];//used to store the rigidbody bones of our ragdoll

function Start () {

boneRig = gameObject.GetComponentsInChildren (Rigidbody); //grabs the rigidbodies of our bones to start

}

function killRagdoll () {

for (var ragdoll : Rigidbody in boneRig) {

ragdoll.isKinematic = false; //disables the animated ragdoll and turns it into just a regular ragdoll with no movement
}
GetComponent(Animator).enabled=false; //disables the mecanim animator so our character no longer has any animations playing
}

 

 

For those who want a C# version for Unity 5 with a simple boolean you can find it below:

 

ragdoll.cs
using UnityEngine;
using System.Collections;

public class ragdoll : MonoBehaviour {


		public Component[] bones;
		public Animator anim;
	    public bool isDead;
	    
		
		// Use this for initialization
		void Start () {
			
		bones = gameObject.GetComponentsInChildren<Rigidbody> ();	
		anim = GetComponent<Animator> ();
	
			
		}
	void Update ()

	{
		if (isDead)
			killRagdoll ();

	}
		
		// Update is called once per frame
		void killRagdoll () 
		{
			foreach (Rigidbody ragdoll in bones)
			{
				ragdoll.isKinematic = false;
			}
			
			anim.enabled = false;
		}
	}

 

 

Jonathan Gonzalez

I love all things in game development and want to contribute by teaching others how to create games. I'm always looking to help others create awesome digital worlds. I've been a hardcore gamer since I was a kid and now it's my turn to create awesome digital experiences.

More Posts - Website

Follow Me:
TwitterYouTube

Comments

  1. Nice tutorial, thanks!

  2. any chance of the source?

    • Jonathan Gonzalez says:

      You mean the project files? I cannot provide those as the packages needed are not mine so I’m not able to distribute them. If you’re stuck on something let me know and I’ll try to help.

      • No problem. My issue is my character us is running quite fast. It’s actually using the forward run from the mocap data. When I turn him to ragdoll the model glitches his ass comes right out. Parts of the chest elongate etc. It’s fine if I kill him while walking. I’ve been stuck on this for weeks

  3. how to apply bonerig to the charcter. someone help me

  4. Got it…

  5. I’m getting this error ” Assets/female chr/RAGDOLLCONTROLLER.js(13,10): BCW0028: WARNING: Implicit downcast from ‘UnityEngine.Component’ to ‘UnityEngine.Rigidbody’ ” , and the ragdoll doesn’t initiate ?!?

    • The script provided is a bit outdated. I uploaded a C# version of it that is more up to date with Unity 5. The reason the ragdoll doesn’t initiate is because nothing is calling the killRagdoll function. So I just added in a simple boolean that you can toggle in the inspector panel to see how that works. Although this would typically work with the other scripts in conjunction for it to really work as indicated in the tutorial.

      • Thx for the quick reply! I get no errors or warnings this time, but the ragdoll still doesn’t initiate. There is colision with the cannonball but he is still animating.

        • There’s a lot of things to check. You need to determine if everything is setup properly. The C# script is a standalone script, so if you’re using that all you need to do is check the “isDead” boolean from the inspector. The JS files all work together. So either you’ll have one C# file or multiple JS files.

      • Nevermind got it working. Forgot to tag the bones!! Do you think it would be posible to make something similar to this “Physics.IgnoreCollision(clone.collider, transform.root.collider);” but to refer to the ragdoll???so one could have a ragdoll with a capsule collider?

        • I’m a little confused on what you’re asking. The ragdoll is just the character with colliders and rigidbodies applied. It’s the same character in the scene you’re just enabling or disabling components. When you create the ragdoll using the ragdoll wizard it’ll add capsule colliders to the bones. If you click on any of the bones you added in the ragdoll wizard you should see a capsule collider along with a rigidbody on each bone.

          • I was refering to the character controller capsule (ThirdPersonController) so you could have your character perform actions but when an event is triggered(collision and such), the ragdoll would be enabled! What i meant is to make the ragdoll ignore collision with that capsule just like you did with the bullet (clone) ???

          • Did you watch all the videos? It seems like you’re asking about everything covered in the videos. The character has animations and a ragdoll. It’s only when we hit him with the bullet or whatever object we want that it turns off the animations and enables the ragdoll. There is no ignore collisions. We’re just specifying what object needs to hit our character in order to enable the ragdoll. Until that specific object collides with our character he will still have all the animations available and can do whatever you want him to do.

  6. Hey quick question, I’m using the C# script and was wondering what is the best way to go about triggering the boolean to activate the ragdoll when the bullet prefab collides on to it.

    Everything works great its just that I’m struggling to get my bullet prefab to trigger the “isDead” boolean, I tried communicating between scripts through killRagdoll function but I’ve been learning C# as I go and not sure how to wrap my head around this particular issue.

    • Make sure your bullet prefab has the collision function script applied to it. Without that working properly you won’t get the ragdoll effect to work. You can use “Debug.Log(“Bullet has impacted”);” within the collision function to ensure the collision is actually being met. If that works then you can check the send message portion of the script to determine if that’s the issue.

      • I’ve been using OnCollisionEnter, I couldn’t locate the “Send Message” in the C# script.
        I tried to create a public variable to insert the ragdoll.cs instead the inspector only allows me to insert the game object that has the ragdoll.cs attached to it [Referring to public Ragdoll x] although the ragdoll prefab has the tag “Enemy”.

        enemyHit.cs :

        using UnityEngine;
        using System.Collections;

        public class enemyHit : MonoBehaviour {

        public Ragdoll x;

        public void OnCollisionEnter(Collision col)
        {

        Ragdoll x = GameObject.Find (“Enemy”).GetComponent ();

        if(col.gameObject.name == “Enemy”)
        {
        Debug.Log(“Bullet has impacted”);
        x.isDead = true;
        }
        }

        }

        • Send message is part of the collision script applied to your projectile. It’s the first script available in this post. It’s in Javascript but it can be easily converted to C#. Also you’re declaring Ragdoll as a variable type, which it isn’t. So converting the C# script function needed:

          void OnCollisionEnter (Collision col) {

          if(col.gameObject.tag == “ragdollBones”) {

          gameObject.Find(“Ragdoll”).SendMessage(“killRagdoll”);

          }
          Destroy(gameObject, 3);

          }

          Assuming your character has a tag of “ragdollBones” and is named “Ragdoll” along with the C# script with a public function called “killRagdoll”.

  7. A little answer its simple, i just need a c#script to make activate ragdoll with the press of a button and the same botton return him to static, but i cant get it, you think you could help me? im using this script, but it only make it ragdoll doesnt bring him back:

    using UnityEngine;
    using System.Collections;

    public class Caida : MonoBehaviour {
    public SkinnedMeshRenderer modelo;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
    if (Input.GetKeyDown(KeyCode.A)){
    modelo.enabled = false;

    if (Input.GetKeyDown(KeyCode.D)){
    modelo.enabled = true;
    }
    }
    }
    }

    • It’s something you’ll have to experiment with as I haven’t done it myself. If you notice we disabled certain components like the animator and set ‘isKinematic’ to false. I’d recommend reversing these to get something similar.

  8. Thanks, you helped me a lot

  9. Hi Jonathan for this good tutorial which helped me. However I have a little problem which I woud like to submit. When my character passes to ragdoll, it has a strange behavior – a violent reaction like if it has been hited by a train 🙂 I assume that there is a little problem with some colliders. I would like to smooth this behavior. Do you have an idea? Thank you and have a nice day ++

    • More than likely the colliders are intersecting so when the ragdoll was enabled all the colliders violently oppose each other creating that effect. Adjust the size of each collider so they just barely fit and give it another try.

      • Finally I solved my problem by deactivating the controller which I forgot on this character. Now it works fine. Thank you for your help ++

  10. Hi Jonathan, thanks for the tutorial, this is a lot for me to start with, although I have a problem setting it up properly, it seems the collision is only working when I disable the animator of ragdoll in the inspector, when the animator is active function killRagdoll is not working at all, am I doing something wrong? Thanks in advance!

    • The way I would change it now is to just combine it within the one script for the projectile instead of in the separate script. You’d detect when you hit a collider on the character then disable the collider. So you’d have something like this:

      if (col.gameObject.CompareTag (“head”))
      col.gameObject.GetComponent ().enabled = false;

      You could also have a reference to the other script and just call the function from that script right after the animator is disabled. All we’re doing in this tutorial is disabling the animator and turning all rigidbodies to non-kinematic so they just fall with physics.

      • Thanks a lot for your time and help, I have finally got this working. Now when the ragdoll falls I’m trying to make a transition from ragdoll pose back to mecanim after a set amount of time, It seems complicated to me, do you think there is any easy way of doing this? I really appreciate your help, thanks again.

        • It’s not something I’ve personally done but I have seen it. The way I would do it is to just do the complete opposite once you detect that the character has hit the ground. Maybe have a script on the torso collider that detects the ground using something like “OnCollisionStay” for 5 seconds, you could also get more specific (back or front) using a raycast to detect distance. If so then you make all the rigidbodies kinematic, turn the animator back on and also start playing the “get up” animation.

          • thanks, I should be fine now, thanks for all your help you are a really nice guy! maybe you should consider making a tutorial on that, I think many people are struggling to get some nice physics in their games.
            Peace out! 🙂

Trackbacks

  1. […] Mechanim –> Ragdollhttp://www.xenosmash.dreamhosters.com/mecanim-ragdoll-unity-3d/ […]

Speak Your Mind

*