Unity 5.x Animation Cookbook - Maciej Szczesnik - E-Book

Unity 5.x Animation Cookbook E-Book

Maciej Szczesnik

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

A recipe-based guide to give you practical information on Unity 5.x animation techniques and tools

About This Book

  • A straightforward and easy-to-follow format.
  • A selection of the most important tasks and problems.
  • Carefully organized instructions to solve problems efficiently.
  • Clear explanations of what you did.
  • Solutions that can be applied to solve real-world problems.

Who This Book Is For

This book is for Unity developers who have some exposure to Unity game development who want to learn the nuances of animation in Unity. Previous knowledge of animation techniques and mecanim is not necessary.

What You Will Learn

  • Importing animations to Unity
  • Work with different animation assets and components
  • Create, visualize, and edit animated creatures
  • Animating game cut scenes
  • Design character actions and expressions
  • Create gameplay by animating characters and environments
  • Use animations to drive in-game logic

In Detail

This recipe-based practical guide will show you how to unleash the power of animation in Unity 5.x and make your games visually impeccable. Our primary focus is on showing you tools and techniques to animate not only humanoid biped characters, but also other elements. This includes non-humanoid character animation, game world creation, UI element animation, and other key features such as opening doors, changing lights, transitioning to different scenes, using physics, setting up ragdolls, creating destructible objects and more.

While discussing these topics, the book will focus on mecanim, the Unity 3D animation tool, and how you can use it to perform all these tasks efficiently and quickly. It contains a downloadable Unity project with interactive examples for all the recipes. By the end of this book, you will be confident and self-sufficient in animating your Unity 3D games efficiently.

Style and approach

This practical no-nonsense guide is recipe-based with real-world examples of almost all the techniques mentioned.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 385

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Unity 5.x Animation Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book 
Errata
Piracy
Questions
1. Working with Animations
Introduction
Importing skeletal animations
Getting ready
How to do it...
How it works...
There's more...
Configuring generic and humanoid rigs
Getting ready
How to do it...
How it works...
There's more...
Creating and assigning an Animator Controller
Getting ready
How to do it...
How it works...
See also
Creating animation transitions in Animator Controller
Getting ready
How to do it...
How it works...
There's more...
Using parameters to control the animation flow
Getting ready
How to do it...
How it works...
There's more...
Using animations from multiple assets
Getting ready
How to do it...
How it works...
Looping, mirroring and offsetting the animations
Getting ready
How to do it...
How it works...
There's more...
Adjusting the playback speed of animations
Getting ready
How to do it...
How it works...
There's more...
Using override animator controllers to animate different types of characters
Getting ready
How to do it...
How it works...
Importing object animation from a 3D package
Getting ready
How to do it...
How it works...
2. Working with the Animation View
Introduction
Using the Animation View to create a flickering light
Getting ready
How to do it...
How it works...
There's more...
Blending light colors with the Animation View and the Animator Controller
Getting ready
How to do it...
How it works...
Animating an object's world position - creating a moving platform
Getting ready
How to do it...
How it works...
There's more...
Animating object's local position - creating automatic doors
Getting ready
How to do it...
How it works...
See also
Using the Hierarchy to animate local rotation - creating an orbiting planet
Getting ready
How to do it...
How it works...
There's more...
Animating triggers - creating a death trap
Getting ready
How to do it...
How it works...
There's more...
Creating an elevator triggered by player input
Getting ready
How to do it...
How it works...
There's more...
3. 2D and User Interface Animation
Introduction
Exporting a 2D sprite animation from a 3D package
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a frame-by-frame sprite animation with the Animation View
Getting ready
How to do it...
How it works...
Creating a 2D sprite doll animation with the Animation View
Getting ready
How to do it...
How it works...
Using the Animator Controller to play sprite animations
Getting ready
How to do it...
How it works...
There's more...
Creating a fade out - fade in transition with the Animation View
Getting ready
How to do it...
How it works...
Creating a swipe transition with the Animation View
Getting ready
How to do it...
How it works...
Using filled images for creating animated progress bars
Getting ready
How to do it...
How it works...
There's more...
Using Mecanim states for animating UI button states
Getting ready
How to do it...
How it works...
There's more...
4. Character Movement
Introduction
Using Blend Trees to blend walk and run animations
Getting ready
How to do it...
How it works...
There's more...
Using root motion to drive Rigid Body characters' movement with animations
Getting ready
How to do it...
How it works...
There's more...
Using root motion to steer a character
Getting ready
How to do it...
How it works...
Using animations for better looking transitions
Getting ready
How to do it...
How it works...
There's more...
Using root motion for a 180 degrees turn
Getting ready
How to do it...
How it works...
There's more...
Making a character jump with 3-phase animation
Getting ready
How to do it...
How it works...
There's more...
Using root motion to drive a NavMesh Agents' movement with animations
Getting ready
How to do it...
How it works...
There's more...
Using triggers to grab an edge while jumping
Getting ready
How to do it...
5. Character Actions and Expressions
Introduction
Creating an appear or a disappear animation
Getting ready
How to do it...
How it works...
There's more...
Creating background characters and critters with animation-driven behavior
Getting ready
How to do it...
How it works...
There's more...
Using Blend Trees to create randomized actions
Getting ready
How to do it...
How it works...
There's more...
Using Quaternion.LookRotation() and Animator.SetLookAtPosition() methods to make characters follow an object with their gaze
Getting ready
How to do it...
How it works...
There's more...
Action Points - performing an action in a specified spot
Getting ready
How to do it...
How it works...
There's more...
Synchronizing an animation with objects in the scene
Getting ready
How to do it...
How it works...
There's more...
Using IK for interacting with scene objects
Getting ready
How to do it...
How it works...
See also
Animating facial expressions with Blend Shapes
Getting ready
How to do it...
How it works...
There's more...
6. Handling Combat
Introduction
Using Sub-State Machines in Animator Controller
Getting ready
How to do it...
How it works...
There's more...
Using Animation Events to trigger script functions
Getting ready
How to do it...
How it works...
There's more...
Using transitions from Any State to play hit reactions
Getting ready
How to do it...
How it works...
Using root motion to create a dodge move
Getting ready
How to do it...
How it works...
There's more...
Checking what Animator state is currently active to disable or enable player actions
Getting ready
How to do it...
How it works...
There's more...
Using Animation Events to draw a weapon
Getting ready
How to do it...
How it works...
Using Avatar Masks and animator controller layers to walk and aim
Getting ready
How to do it...
How it works...
There's more...
Using the LookAt() method to aim
Getting ready
How to do it...
How it works...
There's more...
Using Blend Trees to aim
Getting ready
How to do it...
How it works...
There's more...
Detecting the hit location on a character
Getting ready
How to do it...
How it works...
There's more...
7. Special Effects
Introduction
Using Animation Events to trigger sound and visual effects
Getting ready
How to do it...
How it works...
There's more...
Creating camera shakes with the Animation View and the Animator Controller
Getting ready
How to do it...
How it works...
There's more...
Using the Animation View to animate public script variables
Getting ready
How to do it...
How it works...
Using additive Mecanim layers to add extra motion to a character
Getting ready
How to do it...
How it works...
Using Blend Shapes to morph an object into another one
Getting ready
How to do it...
How it works...
Using wind emitters to create motion for foliage and particle systems
Getting ready
How to do it...
How it works...
Using sprite sheets to animate particles
Getting ready
How to do it...
How it works...
Animating properties of a particle system with the Animation View
Getting ready
How to do it...
How it works...
Using waveform of a sound clip to animate objects in the scene
Getting ready
How to do it...
How it works...
See also
Creating a day and night cycle with the Animation View
Getting ready
How to do it...
How it works...
There's more...
8. Animating Cutscenes
Introduction
Using the Animation View to animate the camera
Getting ready
How to do it...
How it works...
There's more...
Changing cameras with animation
Getting ready
How to do it...
How it works...
Synchronizing animation of multiple objects
Getting ready
How to do it...
How it works...
There's more...
Importing a whole cutscene from a 3D package
Getting ready
How to do it...
How it works...
There's more...
Synchronizing subtitles
Getting ready
How to do it...
How it works...
Using root motion to play cutscenes in gameplay
Getting ready
How to do it...
How it works...
9. Physics and Animations
Introduction
Using cloth
Getting ready
How to do it...
How it works...
There's more...
Using rigid body joints
Getting ready
How to do it...
How it works...
Destructible objects
Getting ready
How to do it...
How it works...
Creating a humanoid ragdoll with the ragdoll wizard
Getting ready
How to do it...
How it works...
Creating a generic ragdoll with character joints
Getting ready
How to do it...
How it works...
Applying force to a ragdoll
Getting ready
How to do it...
How it works...
There's more...
Dismemberment
Getting ready
How to do it...
How it works...
There's more...
Getting up from a ragdoll
Getting ready
How to do it...
How it works...
There's more...
10. Miscellaneous
Introduction
Using math to animate an object
Getting ready
How to do it...
How it works...
Using the Lerp() function to animate an object
Getting ready
How to do it...
How it works...
See also
Using the Rotate() function to animate an object
Getting ready
How to do it...
How it works...
There's more...
Preparing motion capture files for humanoid characters
Getting ready
How to do it...
How it works...
See also
Adding behaviors to Mecanim states
Getting ready
How to do it...
How it works...

Unity 5.x Animation Cookbook

Unity 5.x Animation Cookbook

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2016

Production reference: 1160516

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-391-0

www.packtpub.com

Credits

Author

Maciej Szcześnik

Copy Editor

Sameen Siddiqui

Reviewer

Grzegorz Mazur

Project Coordinator

Bijal Patel

Commissioning Editor

Amarabha Banerjee

Proofreader

Safis Editing

Acquisition Editor

Aaron Lazar

Indexer

Rekha Nair

Content Development Editor

Prashanth G Rao

Production Coordinator

Aparna Bhagat

Technical Editor

Murtaza Tinwala

Cover Work

Aparna Bhagat

About the Author

Maciej Szcześnik is an experienced game designer and Unity developer, specializing in gameplay and combat mechanics. His daily responsibilities include motion capture session planning and coordination, creating animation graphs and state machines, and AI design and implementation.

He started his professional career in 2004 at CD Projekt RED—the company best known for the critically acclaimed The Witcher series. Maciej had key roles in the Witcher games, being lead gameplay designer and lead combat designer. He also worked at 11 bit studios, another well-known Polish game development company, famous for the This War Of Mine game.

Maciej gave three talks at the Game Developers Conference and Game Developers Conference Europe. He is also a lecturer at Warsaw Film School, teaching Unity and technical aspects of animation as part of the game development BA course.

I'd like to thank my wife for her support, Kacper Kwiatkowski and Grzegorz Mazur from Vile Monarch for their reviews, Marek Ziemak and Piotr Tomsiński for inspiring discussions about games and animations, and Michał Pieńkowski and Marcin Iwanek for countless RPG and tabletop game sessions. I'd also like to thank all my friends and former coworkers from 11 bit studios and CD Projekt RED for helping me develop my skills.

About the Reviewer

Grzegorz Mazur is a programmer who graduated in information technology from Warsaw University of Technology. He is currently co-boss and technical director at Vile Monarch. Previously, he worked for 11 bit studios, where he was lead programmer of This War of Mine and Sleepwalker's Journey. He specializes in gameplay and AI programming and is a teacher at Warsaw Film School. He is also an amateur musician and board game enthusiast.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

Get notified! Find out when new books are published by following @PacktEnterprise on Twitter or the Packt Enterprise Facebook page.

Preface

This book describes Unity's animation techniques from a designer's point of view. It is focused on achieving interesting gameplay effects and creating game mechanics. Each topic is presented in the form of a short recipe with a list of steps needed to implement the given feature. All the recipes are prepared in the most condensed form—a good basis to build your own solutions on.

This book doesn't cover animating in a 3D package, although you may find some helpful tips regarding Blender 3D in it. A lot of the recipes presented in this book use C# scripting not only for triggering animations, but also for creating interesting motions and effects. If you are a game designer or a Unity developer and would like to know more about what's possible with Unity's animation system, I hope this book will be an interesting read for you. Also, if you have any questions regarding this book or the topics it covers, you can contact me via Twitter (@MaciejSzczesnik). I will be happy to help.

What this book covers

Chapter 1, Working with Animations, describes the tools essential for importing animations from 3D packages. It also covers most of the import settings.

Chapter 2, Working with the Animation View, covers Unity's built-in animation tool, used to animate almost everything apart from characters.

Chapter 3, 2D and User Interface Animation, focuses on animating 2D sprites and UI elements.

Chapter 4, Character Movement, covers different types of movement, using animations and root motion.

Chapter 5, Character Actions and Expressions, is about actions, action points, and facial expressions.

Chapter 6, Handling Combat, covers combat-specific topics, such as using animations for aiming and creating a hit-detection system.

Chapter 7, Special Effects, is not only about particle systems, but also about animating fog, creating wind zones, and even using sound waveforms for animation.

Chapter 8, Animating Cutscenes, describes how to import a cutscene from a 3D package and how to prepare simple cutscenes using Unity's Animation View.

Chapter 9, Physics and Animations, shows how to create ragdolls and break stuff.

Chapter 10, Miscellaneous, is the last chapter and describes a few solutions to common problems—for instance, working with mocap animations in Blender and Unity.

What you need for this book

You need to install Unity 5.x (preferably 5.3 or greater). You also need to have your own animations or download the provided example project. It contains the assets needed to follow each recipe.

Who this book is for

This book is for Unity developers who have some exposure to Unity game development and want to learn the nuances of animation in Unity. Previous knowledge of animation techniques and mecanim is not necessary.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Simply drag and drop the file to your Assets folder."

A block of code is set as follows:

using UnityEngine; using System.Collections; public class Wave : MonoBehaviour { //The anim variable is used to store the reference //to the Animator component of the character. private Animator anim;

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Go to Assets | Import new asset and choose your FBX file."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Unity-5.x-Animation-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book 

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/Unity5xAnimationCookbook_ColoredImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. Working with Animations

This chapter explains the essentials of working with animations in Unity and covers the following topics:

Importing skeletal animationsConfiguring generic and humanoid rigsCreating and assigning an Animator ControllerCreating animation transitions in Animator ControllerUsing parameters to control the animation flowUsing animations from multiple assetsLooping mirroring and offsetting animationsAdjusting the playback speed of animationsUsing override Animator Controllers to animate different types of charactersImporting object animation from a 3D package

Introduction

Unity is a great game engine that implements the animate everything philosophy, which allows you to visualize even the most creative gameplay ideas. Through the course of this book, we will learn a variety of recipes that will help you unleash the power of Unity 5.x animation tools and make your games more fun.

In this first chapter, we will get more familiar with using skeletal animations in Unity. It will guide you through the process of importing such animations, editing them, and assigning them to your in game characters. This knowledge is essential for understanding recipes described in further chapters.

Importing skeletal animations

This first recipe shows how to import a skeletal animation from a 3D package. It assumes that you have an animation already prepared. We are going to bring the file to Unity and show where you can adjust the import settings. We will not jump into too much detail for now to make the import process as quick as possible. We will cover all the settings in further recipes.

Getting ready

Most animations are created in external 3D packages such as Maya, 3ds Max, Motion Builder, or Blender 3D. Make sure you have prepared a 3D model with a skeleton, the model is skinned, and you have created at least one animation. You can also download the provided example; open the project in Unity and go to this folder: Chapter 01 Working with animations\Recipe 01 Importing skeletal animations\Sheep Model. You will find an imported FBX file called Sheep.fbx there.

How to do it...

To import a skeletal animation, you need to follow these steps:

Export a skinned model and its skeleton (called rig in Unity) to FBX format.

Tip

If you are using Blender, you don't have to manually export the file to FBX format. Simply drag and drop the file to your Assets folder. Unity will use Blender FBX exporter in the background. Additionally, you will be able to open the file by double-clicking on it in Unity. After you edit and save it, Unity will reimport it again. It is a very convenient way of editing animations as you don't have to go through the export-import process each time you make a change.

Drag and drop the exported file into any subfolder in the Assets folder in your project or go to Assets | Import new asset and choose your FBX file.Select the imported file and navigate to the Inspector tab. Click on the Rig button:Here you can specify the type of the rig to use. For bipedal characters, use the Humanoid option, for all the rest choose Generic. We use a sheep model in this example, so we need to choose the Generic rig. Differences between those options are described in the How it works section.Leave all the other inputs as defaults.Click on the Animations button. If an Unapplied import settings window appears, click on Apply.Make sure the Import Animation checkbox is checked.Click on the Apply button in the lower right corner of the Inspector (just above the Animation Preview). You may need to scroll the Inspector down.You should be able to see all imported animation clips as child assets of your imported FBX file.

How it works...

Unity uses four different rig configurations:

Generic rig: This one is used for quadrupeds, spiders, and other non-humanoid characters. It uses Unity's Mecanim system for controlling animation flow. It can use root motion if you provide a Root node—a bone responsible for character movement.Humanoid rig: This one is used for humanoid characters only. It also uses Mecanim system for controlling animation. If you are using Humanoid rigs, you have more options for importing animations. The biggest advantage is automatic animation retargeting—you can use the same animation clip on various types of humanoid characters (for example, a dwarf and a troll).Legacy: This option is used mostly for backward compatibility with previous versions of Unity. It is similar to the Generic rig but uses scripts instead of Mecanim for controlling animation flow. I recommend using Generic rig instead.None: This last option turns off the rig and disables animation import.

We will discuss differences between Generic and Humanoid rigs further in the next recipe.

There's more...

Imported animation clips are also listed in the Clips section of the Animations tab.
You can add new clips by clicking on the plus button below the Clips section. You can also remove clips by clicking on the minus button.You can rename each clip by using the input field above the Source Take drop-down menu.You can choose the source take (the animation stored in your FBX file) for each animation clip with the Source Take drop-down menu.You can also trim the animation clip by editing the Start and End input fields.

Tip

If you are using Blender, make sure to rotate the rig -90 degrees in the X axis, apply the rotation in Blender and then rotate it again, +90 degrees in the X axis. The rotation of the rig in Blender should be: 90 X, 0 Y, and 0 Z. Your model should be facing the -Y axis in Blender (when you change the view to FRONT, you should see the face of your character). Blender and Unity use different axes alignment: in Blender, Z is up and Y is back; in Unity Z, is front and Y is up. This little trick solves the problem. Your model after import should have 0 rotation and should be facing the Z axis. It is important for moving objects (such as characters) and rig configuration. If you don't do this, your model will have -90 X rotation after the import.

Configuring generic and humanoid rigs

This recipe shows how to configure two most frequently used rig types: Generic and Humanoid. We will go through all the available options for both of them.

Getting ready

As previously mentioned, make sure you have prepared two animated characters. One of them should be a humanoid and the other a non-humanoid, a quadruped for instance. You can also download the provided example Unity project and go to the Chapter 01 Working with animations\Recipe 02 Configuring generic and humanoid rigs\Rigs directory.

You will find there three FBX files: 

Generic.fbxHumanoid.fbxQuadruped.fbx

If you are creating your characters from scratch, the bones hierarchy of your humanoid rig is important for Unity to recognize the rig as a humanoid. It should follow this pattern:

HIPS -> SPINE -> CHEST -> NECK -> HEAD HEAD -> EYE (for left and right eyes) HEAD -> JAW HIPS -> UPPER LEG -> LOWER LEG -> FOOT -> TOES (for left and right legs) CHEST -> SHOULDER -> ARM -> FOREARM -> HAND (for left and right hands) HAND -> PROXIMAL -> INTERMEDIATE -> DISTAL (for five fingers in left and right hands)

The hip bone is the root bone of the humanoid character. Fingers, shoulders, chest, neck, eyes, jaw, and toes are optional bones. Your humanoid character will work without them.

You should also remember to model the character in a T-POSE. It should face the Z axis in Unity (if your 3D software uses different axis alignment from Unity's like Blender, remember about the -90 and +90 degrees rotation trick shown in the Importing skeletal animations recipe). Hands of the character should be flat, palm down, and parallel to the ground along the X axis. A-POSE characters will also work.

How to do it...

To configure a generic rig you need to follow these steps:

Import your animated asset into Unity the same way as in the Importing skeletal animations recipe.Select the asset and choose the Rig tab in the Inspector. Then select the Generic option in the Animation Tab drop-down menu. If you are using the provided example Unity Project, select the Generic.fbx file in the Chapter 01 Working with animations\Recipe 02 Configuring generic and humanoid rigs\Rigs directory.Choose the Create From This Model option from the Avatar Definition drop-down menu.Leave the Root Node option set to None.Leave the Optimize Game Objects option unchecked.Click on the Apply button to complete the configuration.

Humanoid rig configuration has a lot more options:

First, import your skinned humanoid model to Unity the same way as in the Importing skeletal animations recipe.Select the asset and choose the Rig tab in the Inspector. Then select the Humanoid option in the Animation Tab drop-down menu. If you are using the provided example Unity Project, select the Humanoid.fbx file in the Chapter 01 Working with animations\Recipe 02 Configuring generic and humanoid rigs\Rigs directory.Choose the Create From This Model option from the Avatar Definition drop-down menu.Leave the Optimize Game Objects option unchecked.Click on the Apply button.You should see a Configure button with a tick icon near to it.The tick icon shows that Unity was able to automatically recognize the rig hierarchy as a humanoid. If Unity fails to recognize it, automatically a cross will be displayed instead of the tick. If you are using the provided example, you can observe it when you try to set the rig to Humanoid for the Generic.fbx file.

Note

Some quadruped characters can be mistaken by Unity for humanoids. You can find a Quadruped.fbx file in the provided example Unity project. Theoretically, you can set its rig to Humanoid, and Unity will recognize it as valid. This, however, is a mistake—all quadruped characters' rigs should be set to Generic. Setting them as humanoids can cause problems later.

Click on the Configure button to enter the Avatar Configuration Inspector. A new scene will be opened. You should be able to see your model in the scene and bone mapping section in the Inspector tab.Make sure you are in the Mapping section (1). All recognized and assigned bones are shown as green body parts on the displayed dummy character. If a required bone is missing or is not assigned, it will show up as red. You can navigate between the Body, Head, Left Hand, and Right Hand sections by clicking on a corresponding button (2). All bones are displayed in a list (3) for each section. Required bones are marked with circle icons and optional bones are marked with dotted circle icons.You can change the bone assignment by dragging a bone from the Hierarchy tab and dropping it onto a corresponding bone slot in the Inspector tab. Unity will occasionally miss a bone or two (especially fingers); thus, you should always check the bone assignment manually.If your character is not in a T-POSE (is modeled in an A-POSE for instance), a Character is not in T-POSE message will be displayed in the scene view and the character's bones will show up in red. Unity needs the character in a T-POSE for proper humanoid avatar configuration. You can enforce that pose by choosing the Pose |Enforce T-POSE option, found below the bones mapping list.Click on the Apply button and then the Done button to finish configuration.

How it works...

Humanoid rig uses more advanced Mecanim features than the Generic rig. You can find the list of such features below:

Automatic retargeting: This is one of the most important differences between those two rigs. The Humanoid rig uses automatic retargeting, which means that you can have the same animations on different humanoid characters. Your characters can share a group of animations (basic movement or some common actions). It gives you the possibility to buy your animation assets from the Asset Store and easily use them on your characters. Generic rigs don't support this feature. You have to prepare animations for your specific rig or retarget them in a 3D package.Inverse kinematics: This feature lets you control your characters' feet and hands position with scripting. It is useful for making your characters stand on uneven ground or grab an object in the scene. It is a built-in feature for Humanoid rigs in Unity. Generic rigs have to use custom-made solutions.Advanced animation settings: Humanoid rigs have more settings for animation import, such as the mirror option. We will discuss them in depth in the Looping mirroring and offsetting animations recipe.Look at: Unity has a built-in solution for humanoid characters looking at something. You have to write custom systems for generic characters.Additional bones: A lot of people think that they cannot use additional bones with Humanoid rigs. It is not true. If your rig has an animated weapon slot for instance, you can still use it with the Humanoid rig. All you need to do is to find the Mask section in your animation import settings and enable the additional bone for each animation it is used in (you need to use the Transform foldout to find your additional bone).

I highly recommend using Humanoid rigs for all humanoid characters in your game.

There's more...

In the Humanoid rig configuration, you can find the Muscles & Settings section, where you can preview and adjust the movement (muscle) range for your character.
You can preview the range of movement in the Muscle Group Preview section by adjusting the sliders (1). You can preview the range of movement per muscle in the Per-Muscle Settings section. You can also adjust the range here by unfolding a given muscle foldout and using the slider (2). In the Additional Settings section, you can adjust more options of your avatar. These are mainly responsible for the flexibility of your rig. You can set how much a bone can be stretched during animation for instance.The Translation DoF option enables animating bones transition in your Humanoid rig. It is turned off by default, meaning that only rotation of the bones is used in animation.In the Rig tab in the model import settings, you can find some additional options:
Avatar Definition: This option is responsible for creating a new avatar or copying the avatar from another model. The second option is useful for storing animations in multiple files. It will be discussed further in the Using animations from multiple assets recipe.Optimize Game Objects: This option lets you hide all bones from the Hierarchy view. The number of game objects in the game has an impact on the performance. You can still choose a number of bones that will be displayed in the Hierarchy. It is useful for having exposing weapon slots and similar gameplay-related bones while hiding others.Root node: This option is visible only for Generic rigs. It lets you choose the bone responsible for root motion calculation. We will discuss it further in Chapter 4, Character Movement.

Creating and assigning an Animator Controller

Animator Controllers are state machines (graphs) responsible for controlling the flow of animations of any animated object in the game. The same Animator Controller asset can be used by multiple objects or characters. Unity will create an independent runtime copy of the asset for each animated object it is assigned to.

Getting ready

As always, you should have a rigged and animated character ready before we start. Import it into Unity, choose the proper rig type, and put it into a scene. You can download the example Unity project and go to the Chapter 01 Working with animations\Recipe 03 Creating and assigning an animator controller directory. There is a scene called Example.unity there. If you open it, you'll find a Sheep character in the Hierarchy. It has an Animator Controller already created and assigned. You can also use the Quadruped.fbx file from the Chapter 01 Working with animations\Recipe 03 Creating and assigning an animator controller\Rigs directory to follow the recipe step by step.

How to do it...

To create and assign an Animator Controller, follow these steps:

Navigate to the Project View (any directory in the Assets folder) and press  the right mouse button.Choose Create | Animator Controller from the menu. A controller asset will be created. You can name it as you wish.Double-click on the created controller. An Animator tab will appear. It will show the current selected Animator Controller.Here you can add the first animation. Navigate to your imported character in the Project View. Unfold it and drag and drop one of the imported animations into the Animator window. A new state will be created and will be colored orange, showing that this is the default animation state—the state from which your graph starts.Navigate to your character on the scene and select it.Find the Animator component in the Inspector tab. All animated objects have an Animator component added automatically.Find the Controller slot in the Animator component inspector.Drag and drop your Animator Controller asset into the Controller slot of the Animator component.Run the game to see your character play the default state animation of your Animator Controller. If the animation is not looped, it will be played just once and then the character will freeze.You can also select your character in runtime and navigate to the Animator tab to see what animation state the character is currently in. Current animation state will have a blue progress bar displayed.

How it works...

Every animated object in Unity uses an Animator component and an Animator Controller asset. The component is responsible for playing animations in runtime. It has a number of parameters that we have to set or we can use to tweak the component's functionality:

Controller: This is the field we have to attach the Animator Controller asset to. It determines which animation graph the Animator component will use.Avatar: In Unity, Avatars are rig definitions. For instance, if we have multiple files containing animations with the same Generic rig, we should use the same Avatar for all of them. You can find more information about it in the Using animations from multiple assets recipe.Apply Root Motion: With this checkbox, we can turn the root motion on and off. It can be useful when we have animations with root motion but don't want to use the root motion definition for a given character.Update Mode: This parameter tells Unity in which update the animations should be evaluated. The Normal option makes the animations synchronized with the normal Update() call, the Animate Physics option synchronizes animations with the physics FixedUpdate() call, and the Unscaled Time option synchronizes the animation with the normal Update() call, but disables animation time scaling (the animation is played with 100 percent speed regardless of the Time.timeScale variable value).Culling Mode: This parameter tells Unity when to turn off the animation playback on a given Animator. The Always Animate option makes the Animator always play animations (event when off-screen), the Cull Update Transforms option culls Retarget and IK Transforms when the Animator is not visible on screen, and the Cull Completely option disables the animation completely when the Animator is not visible on screen.

The Animator Controller asset stores a graph of animations (animation states) and defines the rules of switching between them, blending them, and so on. The controller (asset) is attached to the component's Controller field (the component is attached to a character prefab or a character placed in the scene). Many objects or characters can share the same Animator Controller if they use the same animations (have the same rigs or are humanoid characters).

See also

If you want to learn how to create animation graphs and control their flow, see the next two recipes: Creating animation transitions in Animator Controller and Using parameters to control the animation flow.

Creating animation transitions in Animator Controller

As mentioned previously, Animator Controllers are state machines containing animations (states). Any given character can be in one such state (play one animation) at a time. To switch between states (animations), you need to create state transitions.

Getting ready

Before we start, you should have an animated model placed on a scene with an Animator Controller assigned. You can find such a model in the provided example Unity project. Go to the Chapter 01 Working with animations\Recipe 04 Creating animation transitions in Animator Controller directory. Open the Example.unity file. You will find a Sheep object in the Hierarchy. It has an Animator Controller assigned. You can open it by double-clicking on the Controller field in the Animator component of the Sheep game object.

How to do it...

To create a state transition in an Animator Controller, follow these steps:

Open the Animator Controller asset.Add at least two states by dragging and dropping two animations into the Animator window. You can also point the cursor at an empty space in the Animator window, press the right mouse button and select Create State | Empty, then select the state, and add an animation to the Motion field in the Inspector.Click on the right mouse button on the state you want to transition from and choose Make Transition.Drag the transition onto the state you want to transition to and click the left mouse button.A default transition will be created. The state will switch after its animation has finished playing. To be able to observe it in gameplay, make sure you transition from the default (orange) state, as only the default state will play when the game starts.

How it works...

State transitions define how we can travel through the graph of animations. They are combined with transition conditions based on Animator Controller parameters; we will discuss the parameters in detail in the next recipe: Using parameters to control the animation flow. Each transition has a set of properties we can adjust. Click on the transition (white arrow) to select it. You can find the transition properties in the Inspector tab (make sure to unfold the Settings foldout):

Has Exit Time: If set to true, this enables the transition only after a given percentage of the animation has been already played. If disabled, the transition will take place instantly after its conditions are met. If you want to create a sequence of animations, set it to true.Exit Time: This is the percentage (0-1 range) of the animation length after which the Has Exit Time condition is met. If you set it to 0.5, for instance, the state will transition after 50 percent of the animation was played.Fixed Duration: This property is combined with the next one, Transition Duration (s). If it's on, the Transition Duration (s) is in seconds, and if it's off, the Transition Duration (s) is in percentage of the animation time.Transition Duration (s)