Jump to content
Site Stability Read more... ×
  • Advertisement
  • 08/07/17 05:55 AM

    How We Optimized Ragdoll Death Animation in Unity

    General and Gameplay Programming




    Hello, everyone.  We are a small indie game studio called Drunken Monday.

    We’ve recently made a game in Unity3d where you run around an arena, rotate around yourself with the huge axe and try to hit other players. Good smash - good kill.

    We used ragdoll animation based on physics to make the deaths look more realistic. And everything was good in the beginning...

    However, when the number of the characters and calculations started growing, the game began working slowly and lagging on older phones. Disabling all physics calculation gave us 50-60 fps and absolute smoothness, but we didn't want to give up the cool ragdoll deaths of the characters.
    One of the solutions was to force the animators to build a pack of death animations. But we had a great idea to record a few ragdoll deaths directly in Unity and then just show the desired animation? Deaths will turn out to be diverse, there will no need to occupy animators, and the most important - everything will be fast, beautiful and realistic.

    What we get:



    The animation clip in the Unity is presented by the AnimationClip class, which contains an array of AnimationCurve. AnimationCurve defines the curve for the changes of one particular property of a particular object, for example, the localPosition.x. Values change in the timeline are described by a number of Keyframe structures.


    The idea is simple: for the each property of the each character object we create an AnimationCurve and store the values of this property on the curve for the each frame. The generated AnimationClip is exported through  AssetDatabase.CreateAsset at the end.

    Let's create the class AnimationRecorderItem to track the each character object. All properties of the monitored object will be described through the dictionary, where the keys are the name of the properties and the values are the animation curves.

    Properties = new Dictionary<string, AnimationCurve> ();
    Properties.Add ( "localPosition.x", new AnimationCurve () );
    Properties.Add ( "localPosition.y", new AnimationCurve () );
    Properties.Add ( "localPosition.z", new AnimationCurve () );
    Properties.Add ( "localRotation.x", new AnimationCurve () );
    Properties.Add ( "localRotation.y", new AnimationCurve () );
    Properties.Add ( "localRotation.z", new AnimationCurve () );
    Properties.Add ( "localRotation.w", new AnimationCurve () );
    Properties.Add ( "localScale.x", new AnimationCurve () );
    Properties.Add ( "localScale.y", new AnimationCurve () );
    Properties.Add ( "localScale.z", new AnimationCurve () );

    For all of the object properties in each frame will be set their current values:

    Properties["localPosition.x"].AddKey (new Keyframe (time, _animObj.localPosition.x, 0.0f, 0.0f));
    Properties["localPosition.y"].AddKey (new Keyframe (time, _animObj.localPosition.y, 0.0f, 0.0f));
    Properties["localPosition.z"].AddKey (new Keyframe (time, _animObj.localPosition.z, 0.0f, 0.0f));
    Properties["localRotation.x"].AddKey (new Keyframe (time, _animObj.localRotation.x, 0.0f, 0.0f));
    Properties["localRotation.y"].AddKey (new Keyframe (time, _animObj.localRotation.y, 0.0f, 0.0f));
    Properties["localRotation.z"].AddKey (new Keyframe (time, _animObj.localRotation.z, 0.0f, 0.0f));
    Properties["localRotation.w"].AddKey (new Keyframe (time, _animObj.localRotation.w, 0.0f, 0.0f));
    Properties["localScale.x"].AddKey (new Keyframe (time, _animObj.localScale.x, 0.0f, 0.0f));
    Properties["localScale.y"].AddKey (new Keyframe (time, _animObj.localScale.y, 0.0f, 0.0f));
    Properties["localScale.z"].AddKey (new Keyframe (time, _animObj.localScale.z, 0.0f, 0.0f));

    But if you record all values for the each frame for the each property of the each object, the output file of the animation will turn out to be too large. Let's introduce the conditions for limiting the minimum changes in comparison with the previous frame. If the object has moved, increased and turned just a little bit, we will not record these changes.

    Completed class: AnimationRecorderItem.cs

    Also, we have to create a manager class AnimationRecorder.

    This script should be executed through the all children of the animated object and create an instance of AnimationRecorder for each of them.
    And also immediately generate and remember relativePath under which it will be saved in AnimationClip.

    According to the documentation,  relativePath is generated as follows:


    Path to the game object this curve applies to. The relativePath is formatted similar to a pathname, e.g. "root/spine/leftArm". If relativePath is empty it refers to the game object the animation clip is attached to.

    The code will look like:

    private List<AnimationRecorderItem> _recorders;
    void Start ()
        Configurate ();
    void Configurate ()
        _recorders = new List<AnimationRecorderItem> ();
        var allTransforms = gameObject.GetComponentsInChildren< Transform > ();
        for ( int i = 0; i < allTransforms.Length; ++i )
            string path = CreateRelativePathForObject ( transform, allTransforms [ i ] );
            _recorders.Add( new AnimationRecorderItem ( path, allTransforms [ i ] ) );
    private string CreateRelativePathForObject ( Transform root, Transform target )
        if ( target == root )
            return string.Empty;
        string name = target.name;
        Transform bufferTransform = target;
        while ( bufferTransform.parent != root )
            name = string.Format ( "{0}/{1}", bufferTransform.parent.name, name );
            bufferTransform = bufferTransform.parent;
        return name;


    To calculate current animation time and record the properties values for the each frame:

    private float _recordingTimer;
    private bool _recording = false;
    void Update ()
        if ( _recording )
            for ( int i = 0; i < _recorders.Count; ++i )
                _recorders [ i ].AddFrame ( _recordingTimer );
            _recordingTimer += Time.deltaTime;


    But the  Update function is called quite often and recording the animation every frame is pretty redundant, so we limit the record. 30 fps should be enough for everyone. 
    We will start recording by tapping on Spacebar.

    private const float CAPTURING_INTERVAL = 1.0f / 30.0f;
    private float _lastCapturedTime;
    private float _recordingTimer;
    private bool _recording = false;
    void Update ()
        if ( Input.GetKeyDown ( KeyCode.Space ) && !_recording )
            StartRecording ();
        if ( _recording )
            if (_recordingTimer==0.0f||_recordingTimer-_lastCapturedTime>=CAPTURING_INTERVAL)
                for ( int i = 0; i < _recorders.Count; ++i )
                    _recorders [ i ].AddFrame ( _recordingTimer );
                _lastCapturedTime = _recordingTimer;
            _recordingTimer += Time.deltaTime;
    public void StartRecording ()
        Debug.Log ( "AnimationRecorder recording started" );
        _recording = true;

    Let’s implement an animation export. We will create the AnimationClip instance and fill it with the collected values.

    private void ExportAnimationClip ()
        AnimationClip clip = new AnimationClip ();
        for ( int i = 0; i < _recorders.Count; ++i )
            Dictionary<string,AnimationCurve> propertiles = _recorders [ i ].Properties;
            for ( int j = 0; j < propertiles.Count; ++j )
                string name = _recorders [ i ].PropertyName;
                string propery = propertiles.ElementAt ( j ).Key;
                var curve = propertiles.ElementAt ( j ).Value;
                clip.SetCurve ( name, typeof(Transform), propery, curve );
        clip.EnsureQuaternionContinuity ();
        string path = "Assets/" + gameObject.name + ".anim";
        AssetDatabase.CreateAsset ( clip, path );
        Debug.Log ( "AnimationRecorder saved to = " + path );

    Completed class AnimationRecorder.cs

    Finally, we will create the  AnimationRecorderRagdollHelper helper class, which function will stop the Animator on the animated object, turn on all collisions, give the object acceleration and start recording our animation. The end of the animation recording will be completed by ourselves. 
    To avoid some artefacts due to scene loading and the initialization of various objects, the script will start working with the specified delay.

    Completed class AnimationRecorderRagdollHelper.cs
    That's all, we add AnimationRecorderRagdollHelper on our character, set the impact force, then start the scene - and watch how the character cheerfully flies around the scene.

    When the cold corpse freezes on the ground - press Spacebar. 



    The script will export our animation to the root of the project.





    We recorded 4-5 animations for each character in this way and choose between them randomly when the character dies.
    P. S. Or not quite randomly.
    Our game is multiplayer, physics is calculated on the server and the vector of impact comes to us. So we select the necessary animation based on the vector which comes to us from the server, simply looking for the closest vector which the animation was recorded.
    Project on GitHub

    " rel="external nofollow">A video of the game on YouTube with some deaths

    Slash Arena: Online ( Facebook )

    Slash Arena: Online ( Steam )


      Report Article

User Feedback

Create an account or sign in to leave a review

You need to be a member in order to leave a review

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

There are no reviews to display.

  • Advertisement
  • Game Developer Survey


    We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a $15 incentive for your time and insights. Click here to start!

    Take me to the survey!

  • Advertisement
  • Latest Featured Articles

  • Featured Blogs

  • Advertisement
  • Popular Now

  • Similar Content

    • By Ruben Torres
      [The original post was published with its original formatting in The Gamedev Guru's Blog]
      Heya, Unity Addressables fan.
      Last week, I posted a short but powerful article detailing three ways Unity Addressables can help you developing better games. The article was very well received, thanks for your active participation.

      Just at the end of that post, you were given the chance to test your knowledge in Unity Addressables through a short quiz.

      The goal I had in mind when creating the quiz was to help you become aware of the areas you might be less familiar with, so you can get to develop your skills where you need the most.
      I'll confess that, initially, I didn't expect many people to go through the quiz. After all, quizzes can be daunting and, as usual, there's this extra babbling coming from me.
      But to my surprise, the quiz results well outperformed my expectations. I'm really happy to see that so many people accepted the challenge. You all rock!
      I got some interesting statistics out of the quiz. Here are some figures I wanted to share with you:
      The greatest part of the people who started it, about 80%, actually were determined enough to finish it The average score was about 12, which is pretty damn good for an API that was only introduced recently Less than 5% of the quiz participants fell in the Troll Guru rank About 50% are part of the Apprentice Guru group Over 40% of the participants scored enough to be Enlightened Gurus But only 5% made it to be considered The Final Boss Guru So, congratulations if you were part of the quiz experience!
      And independently from the score you got, I am sure it will not take you much effort to reach the production-level required score of 20+. I'll be helping you along the path.

      In this post, I will explain the most interesting challenges posed in the quiz. Some answers might differ depending on your particular context, so make sure to comment at the end of the post if you had a complementary experience.

      If you didn't complete the quiz before, do it now before reading further.
      Do not cheat. I'll know.

      What were your results? Are you a Troll Guru, an Apprentice Guru, an Enlightened Guru or The Final Boss Guru? Share your results in the comments section.
      Trusting that you finished it, let's have a look at the questions and some of the answers. The format should be self-explanatory, but I admit I could have chosen less cheesy graphics for it— yes, that's me.

      Question 1: Intense Memory Pressure
      An angry player leaves a 1-star review because your game uses too much memory. You...

       Answer in public, telling the player to upgrade their device and then come back
      This is a popular answer somehow. As much as we might feel like answering this, chances are, we have been too busy (or lazy) to implement a proper architecture. Blaming players for playing with a brick-phone won't get us more sales, so a better strategy is to fix our mess.
       Switch to a more advanced texture compression method, e.g. ETC2 to ASTC
      This is helpful and you should indeed switch to more advanced compression methods, where possible. But this solution will only take you so far. You'll get moderate gains in memory usage and texture quality, but they'll not be enough to cover your memory pressure issues.

       Split your scenes into sub-scenes, so less content is loaded in memory
      In general, sub-scenes used to be a good solution. I've used them in the past with great success. However, if you are having bad reviews already, chances are it is too late to introduce such a massive change in the architecture of your game. Better to look somewhere else.
      Implement an asset lazy-loading mechanism through AssetReferences
      Over 75% of people agreed on this, that's great.
      AssetReferences are likely to give you the biggest gain for the buck. The migration to this workflow is usually straight-forward and much easier than the other alternatives.
      However, be aware that, in some cases, it might be hard to work around the asynchronous requirements of the Unity Addressables API.

      Question 2: Endless Loading Times
      You press the play button. By the time your in-game scene is loaded, your coffee is cold. You...
       Blame the artists and ask them to put every texture into atlases. Also, you buy a faster PC
      10% of the subscribers chose this one. I love you guys.
      Reduce the texture size globally, so asset loading is much faster. You don't submit these meta file changes in your versioning system
      I've done this a few times recently. It works.
      However, the pay to price is high. Your versioning system might go nuts and your changelists will be full of garbage. This is indeed hard to manage, as if you ignore these temporal texture import settings modifications, the real changes will mostly go unnoticed and won't be submitted.
      Create custom scenes that contain just the functionality you are working on
      Creating sub-scenes for faster iterations might be a possibility for your game, but in my experience, they tend to be left unmaintained. With time, they break and one might spend more time fixing them than the gain you eventually had back then.
      Consider implementing sub-scenes only if you don't see these problems in your project.
       Remove direct references and add indirect references instead, so only the required assets are loaded
      Indirect references for the winner.
      Direct references will implicitly ask Unity to load all their content as soon as the script holding them is instantiated. Indirect references, however, gives you full control over the when/how/what. That means, you can delay loading until you need it, if at all, saving you from unnecessary loading times and wasted memory.

      Question 3: What Play Mode Script?
      You are currently implementing materials for your new characters. You want to try Addressables, so in the Play Mode script section of Addressables, you select...
       Fast Mode: we want it always fast, after all
      This is a valid option, but fast mode does no validation at all of important aspects of development, such as asset dependencies and cross-references.
      If there are no substantial changes in the content you're working on, fast mode will be fine. Otherwise, we can do better.
       Packed Play Mode: yes! we want our characters to be packed
      No! The Packed play mode requires you packing the assets every time you do a change in your addressable asset contents, otherwise you'll end up loading the old versions.
      You don't want to be packing every time, it's a huge time sink.
      But you might consider packed play mode once you're done working with addressables content to gain faster iterations, as these assets will require minimum processing while being loaded.
      35% of the Guru Challengers chose this answer.
       Virtual Mode: it sounds safer than fast mode
      Virtual Mode is the option I suggest you using while actively working on your addressable content.
      The virtual mode is fast enough to keep iteration times short and at the same time, it'll give you useful validation checks to avoid screwing it up and finding out the mess way too late.

      Question 4: Oops... Error Diagnosing
      You try Addressables but you don't recall your assets looking pink in your Android device. How weird! You...
       Enable the ADDRESSABLES_LOG_ALL symbol, make a development build and check the logcat logs
      If you came to me with such a description, I wouldn't necessarily take you down this road directly.
      The main issue with adding scripting defines and checking the logs on the device is the time it takes to prepare such a build, deploy it, test it and gather useful information from the logs.
      There are indeed better ways to tackle this, but certainly keep this as a backup option if they fail to give you an accurate diagnosis of the problem.
      Set the play mode script to Packed Play Mode and run it in the editor to further diagnose the issue with the Addressable Profiler
      Emulating as much as you can the environment in which the content will be displayed is my preferred option, as it takes the least total amount of time. You do this by selecting the packed play mode in the main Addressables Window settings. The Unity Editor will load the addressable resources directly from the built content, so this is expected to give you a similar behavior than on the device, as long as the editor can load such a content.
      You can also try running it in virtual play mode, which does some validation on top of the traditional asset loading pipeline for addressables.
      Don't forget to count on the Addressable Profiler's help, a tool that will inform you about the addressable operations that are taking place at all times in your game.
      This answer was correctly chosen by 66% of the participants.
       Post in StackOverflow and Unity Answers
      12% of you see value in posting questions on these platforms, as there are always people willing to help. But preparing a reproduction project, posting and refreshing your screen with F5 is likely to take you much longer than just diagnosing and fixing the problem yourself. Trust me, this should be your last resort.

      Question 5: Heavy Video Packing
      You want your mp4 trailer video to be included in your game. You...
       Toss it into the StreamingAssets folder
      The StreamingAssets directory works just fine, especially when coupled with famous video plugins you find in the store. The assets stored in that directory are not packed together like Resources do but rather left as individual files when your game is installed. Its simplicity and easy I/O is the reason it is the default method of playing video.
      The biggest con is that the assets stored in StreamingAssets are forcefully packed in your distributed game from the beginning, so they are likely to take a lot of space in your build.
      Why would your users have to wait 5 minutes longer just to download the credits video that will be played at the end of a 30+ hours game?
       Mark it as Addressable, add a "videos" label to it
      Sure, making it addressable sounds cool. But adding a "videos" label to it?
      Usually, labels are used to download all assets belonging to that label category at once. Unless you have a very specific use case, doing this is not likely to help your project.
       Mark it as Addressable, adding it to a "videos" group with the following attributes: static content, no compression
      Videos are not likely to change, so making them static makes sense. Also, there's no need to compress them, as the used video codec should already offer you compression. Adding LZ4 or LZMA compression on top of this already-compressed content will only incur in CPU overhead. Your users' battery will drain faster as well. I'm sure your players wouldn't appreciate it.
       Mark it as Addressable, adding it to a "videos" group with the following attributes: dynamic content, LZMA compression
      Dynamic, compressed content is by far the most commonly chosen answer. But it is a misleading one.
      For the reasons stated above, you should avoid using compression on already compressed content. And videos are often enough very static, so by marking that group dynamic you wouldn't be helping your asset building workflows.
      Most people (46%) thought this was to best option.

      Question 6: Memory on Instance Releasing
      You loaded your asset once through LoadAssetAsync. Now you're done with it, so you...
       Call Addressables.Release, so the memory is immediately released
      There's no guarantee that the memory will be freed right away, as the current documentation correctly points out. But do not worry about it too much, it will be correctly freed by Unity. 23% popular.
       Call Destroy, we better make sure we free that memory up
      Addressables is, as of now, unaware of traditional Unity instantiation and destroy mechanisms. If you do so by yourself, you are doing it at your own risk and bookkeeping. If you mess it up, the API and OS are unlikely to be happy about it. And you will know.
       Call Addressables.Release, so the memory is released at some point in the future
      The documentation implies that the memory occupied by addressable assets will be freed at some point in the future after calling the Unity addressables release method.
      You can count on Unity smartly deciding when it is time to do just so (e.g. low memory situations, Resources.UnloadAllUnusedAssets, etc.). You guys got this one right!

      Question 7: Loading with LoadAssetAsync
      You're excited about doing your first Addressables.LoadAssetAsync. So you call it and use its returned handle like...
       while (handle.Status == AsyncOperationStatus.Succeeded) ;
      I confess to you that I've tried this method to try to force a synchronous behavior out of the Addressables API (e.g. Photon Networking under Unity Addressables).
      But you can guess what happened after seeing the answer's smiley. My computer's fan started spinning insanely fast and I had to reboot the computer as the OS became utterly unresponsive. I'm not trying this again any time soon, thanks.
      Doing this loop is likely to cause a deadlock, as part of the loading process is executed in Unity's main thread. And that line of code is the easiest way to block your main thread.
       await handle.Task; or yield return handle;
      These two solutions are asynchronous ways of waiting for the loading process to finish before continuing with our code. That's great stuff for you and me, as they offer great readability and are easy to maintain.
      However, be aware they incur on some performance penalty.
       handle.Completed += OnLoadCompleted;
      This is the simplest and yet most powerful option to do something after the asset has been loaded into memory.
      Keep in mind, though, that you're introducing lambdas and/or callbacks. They will reduce the readability of your code and therefore make your programming style more dangerous. Unless you are a pro, of course.

      Question 8: Migrating to Better Workflows
      You have a bunch of skyboxes living as direct references in your Skybox manager as a list of materials. Those are eating all your memory, so you...
       Move them into the Resources folder and start using Resources.Load as you need them
      No! Bad boy!
      Don't ever use the Resources directory for heavy assets. They are a major cause of pain, tears and  burnouts in large scale projects. It is indeed surprisingly easy to misuse the Resources API. Read more info on why it is so here
       Put all skyboxes in an asset bundle that you will load appropriately
      Asset bundles were a much-needed solution back then. But we have better solutions now with Unity Addressables.
      The issue is that working with asset bundles is way more tedious and expensive to implement and maintain than just using Unity Addressables. Unless you're doing a port and you don't want to touch much of the original systems, try to avoid them.
       Replace the list of skybox materials with a list of AssetReference's and load them as you need
      Using Unity Addressables is probably the best option to tackle this kind of memory issues.
      One of the reasons it is such a silver bullet is because you can easily migrate from the most popular approaches of managing content such as direct references, resources API, additive scenes and asset bundles.
      Unity Addressables are a simpler way to develop more efficient games.
       Decrease the skybox texture sizes
      Tweaking the texture import settings works up to a point. This has an upper ceiling limit, as you cannot infinitely go lower in memory usage (and quality) without re-categorizing your 3d game into pixel-art. This just doesn't scale well.

      Chances are very high that you didn't reach the rank of The Final Boss Guru.
      But that's good, because that means there's massive room for improving and optimizing the way you develop and ship games. And what is more important, your players will appreciate the expertise you build in each of these areas. The only place you want to read 1-star reviews is at the app store of your competitor's game.
      Given the importance of delivering enjoyable experiences to your players, I will share something with you.
      Between you and me: I have a work-in-progress plan for maximizing the potential of your game with Addressables. In the upcoming weeks, I will be revealing to you more information about the Unity Addressables level-up program I'm developing. That program is going to get you to the production level you need to deliver the games people will deeply enjoy (purchasing and) playing.
      To make sure you don't miss on the upcoming content, subscribe now to the newsletter. I'll keep you posted.
      Till then, comment below on what you would like to learn the most and also how you plan to use Unity Addressables in your project.
      See you soon on the blog!
    • By RoKabium Games
      On Lelantos you can use Portals to quickly go from one side of the map to the other. Each Portal has a number that once discovered will show up on the mini-map to help you keep track of where you are. Just be careful when using these teleportation devices, you never know what waits on the other side of the gate!
    • By Erz0
      Flappy Monster is back with a Remastered Version , new mechanics, graphics and rewards are waiting for you to come back.
      Touch and Fly , simple as that , mentain the rigidbody velocity of the flappy monster and get into a world full of danger. OZN , ASTEROIDS. You must protect yourself from danger !
      Don't worry , you have unlimited Ninja shurikens to throw into obstacles 

      1.0.1 VERSION NEW Features
      • NEW LEVELS
      • POWERS
      • COOL MUSIC
      • SHOP

      APP LINK: https://play.google.com/store/apps/details?id=com.erzo.flyingmonsterarcade
      Contact us at erz0development@gmail.com for errors, suggestions, business and privacy policy.
    • By khawk
      In a blog post yesterday, Unity announced new pricing for Unity Pro and Unity Plus subscriptions. The increase starts at the beginning of 2020 and does not affect existing Unity subscriptions. Any changes to current subscriptions, however, will end up being affected by the price increase.
      According to the blog, Unity is increasing prices "in order to continue investing in new technology, features and services that will benefit all Unity creators".
      Read more from the Unity blog here.

      View full story
    • By khawk
      In a blog post yesterday, Unity announced new pricing for Unity Pro and Unity Plus subscriptions. The increase starts at the beginning of 2020 and does not affect existing Unity subscriptions. Any changes to current subscriptions, however, will end up being affected by the price increase.
      According to the blog, Unity is increasing prices "in order to continue investing in new technology, features and services that will benefit all Unity creators".
      Read more from the Unity blog here.

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!