• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Reefer · Oct 22, 2014 at 07:06 PM · animationjavascriptmecanimanimationschanging

About mecanim and changing animations, there must be more clever way of doing this.

I'm trying to learn Mecanim, and it's going pretty well other than I'm having hard time to understand which would be best way to change animations. Currently I'm using boolean parameters on Animator and Input.GetKey on my code, but this my way has f*uckloads of If statements. So, a better way of doing this would be appreciated.

Also, I'm having problem with my jump animation. After jumping it won't get back to idle animation, it just stays in end pose of jumping animation, even though I have transitions back to Idle from Jump. All other animations do get back to idle animation after I stop pressing the right key.

Here's my current code, (if statements for animations start pretty much right after function Update) Sorry about spaghetti code, there's not much of comments to explain what happens where (except the parts that has something to do with animations)

 var mainCam : GameObject;
 //Old animation stuff, not needed
 // var animObject : GameObject;
 // var fallAnimGO : GameObject;
 var moveSpeed : int = 2;
 var crouchSpeed : int = 1;
 var runSpeed : int = 5;
 var jumpSpeed : int = 10;
 var gravity : int = 20;
 var maxEnergy : float = 10;
 var energyRegenRate : float = 1;
 var Smooth : float = 5;
 
 var grounded : boolean = false;
 var running : boolean = false;
 
 var energy : float;
 private var originalSpeed : int;
 private var hitCeiling : boolean = false;
 public var moveDirection = Vector3.zero;
 private var controller : CharacterController;
 controller = GetComponent(CharacterController);
 
 private var IntialPosition : Vector3;
 private var InitialHeight : float;
 private var CrouchingHeight : float;
 private var InitialCenter : Vector3;
 private var CrouchingCenter : Vector3;
 private var defCamPos : float = 0;
 private var bobSpeed : float;
 private var bobAmount : float;
 private var timer = 0.0;
 private var camPos : float;
 private var crouching = false;
 
 internal var animator : Animator; //Mecanim animator
 
 function Start()
 {
     originalSpeed = moveSpeed;
     energy = maxEnergy;
     defCamPos = mainCam.transform.localPosition.y;
     camPos = defCamPos;
     InitialHeight = controller.height;
     CrouchingHeight = InitialHeight - .5f;
     InitialCenter = controller.center;
     CrouchingCenter = InitialCenter + Vector3.down * 0.25f;
     isCrouching = false;
     animator = GetComponent(Animator);
 }
 
 function Awake()
 {
     //Old animation stuff, not needed
     //animObject.animation.wrapMode = WrapMode.Loop;
 }
 
 function Update()
 {
     if(controller.isGrounded)
     {
         moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
         moveDirection = transform.TransformDirection(moveDirection);
         moveDirection *= moveSpeed;
         
         //Setting up mecanim animations
         //Jumping animation
         if(Input.GetKeyDown(KeyCode.Space))
         {
             animator.SetBool("jump", true);
             animator.SetBool("run", false);
             animator.SetBool("walk", false);
             animator.SetBool("idle", false);
             Jump();
         }
         
         if(Input.GetKeyUp(KeyCode.Space))
         {
             animator.SetBool("jump", false);
             animator.SetBool("run", false);
             animator.SetBool("walk", false);
             animator.SetBool("idle", true);
         }
         //Walking animation
         if (Input.GetKey(KeyCode.W))
         {
             animator.SetBool("jump", false);
             animator.SetBool("run", false);
             animator.SetBool("walk", true);
             animator.SetBool("idle", false);
         }
         
         if (Input.GetKeyUp(KeyCode.W))
         {
             animator.SetBool("jump", false);
             animator.SetBool("run", false);
             animator.SetBool("walk", false);
             animator.SetBool("idle", true);
         }
         // Running animation
         if(Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.W))
         {
             animator.SetBool("jump", false);
             animator.SetBool("run", true);
             animator.SetBool("walk", false);
             animator.SetBool("idle", false);
         }
         
         if(Input.GetKeyUp(KeyCode.LeftShift) && Input.GetKeyUp(KeyCode.W))
         {
             animator.SetBool("jump", false);
             animator.SetBool("run", false);
             animator.SetBool("walk", false);
             animator.SetBool("idle", true);
         }
         //Backwards walking
         if (Input.GetKey(KeyCode.S))
         {
             animator.SetBool("jump", false);
             animator.SetBool("run", false);
             animator.SetBool("walk", true);
             animator.SetBool("idle", false);
         }
         
         if (Input.GetKeyUp(KeyCode.S))
         {
             animator.SetBool("jump", false);
             animator.SetBool("run", false);
             animator.SetBool("walk", false);
             animator.SetBool("idle", true);
         }
         //If LeftShift & S down, play running animation
         if(Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.S))
         {
             animator.SetBool("jump", false);
             animator.SetBool("run", true);
             animator.SetBool("walk", false);
             animator.SetBool("idle", false);
         }
         //If LeftShift & S up, don't play running animation
         if(Input.GetKeyUp(KeyCode.LeftShift) && Input.GetKeyUp(KeyCode.S))
         {
             animator.SetBool("jump", false);
             animator.SetBool("run", false);
             animator.SetBool("walk", false);
             animator.SetBool("idle", true);
         }
         
         if(controller.velocity.magnitude > (moveSpeed - 1) && controller.velocity.magnitude < (runSpeed - 1))
         {
             //Old animation stuff, not needed
             //animObject.animation.CrossFade("Walk");
             bobSpeed = 0.25;
             bobAmount = 0.005;
             
         }
         else if(controller.velocity.magnitude > (runSpeed - 1))
         {
             //Old animation stuff, not needed
             //animObject.animation.CrossFade("Run");
             bobSpeed = 0.29;
             bobAmount = 0.01;
         }
         else
         {
             bobSpeed = 0;
             bobAmount = 0;
         }
         if(Input.GetKey(KeyCode.LeftShift) && (Input.GetAxis("Horizontal") || Input.GetAxis("Vertical")))
         {
             if(energy > 0)
             {
                 if(!crouching)
                 {
                     Run();
                 }
                 else
                 {
                     moveSpeed = crouchSpeed;
                 }
             }
             else
             {
                 running = false;
                 if(!crouching)
                 {
                     moveSpeed = originalSpeed;
                 }
                 else
                 {
                     moveSpeed = crouchSpeed;
                 }
             }
         }
         else
         {
             running = false;
             if(energy < maxEnergy)
             {
                 energy += energyRegenRate * Time.deltaTime;
             }
             if(!crouching)
             {
                 moveSpeed = originalSpeed;
             }
             else
             {
                 moveSpeed = crouchSpeed;
             }
         }
         
         var camHeight : Vector3 = new Vector3(mainCam.transform.localPosition.x, camPos, mainCam.transform.localPosition.z);
         var smoothHeight  = Vector3.Lerp(mainCam.transform.localPosition, camHeight, Time.deltaTime * Smooth);
         mainCam.transform.localPosition = smoothHeight;
         
         if(Input.GetKeyDown("c"))
         {
             if(!crouching)
             {
                 controller.height = CrouchingHeight;
                 controller.center = CrouchingCenter;
                 camPos = defCamPos - .5f;
                 crouching = true;
             }
             else
             {
                 controller.height = InitialHeight;
                 controller.center = InitialCenter;
                 camPos = defCamPos;
                 crouching = false;
             }
         }
         waveslice = 0.0; 
         horizontal = Input.GetAxis("Horizontal"); 
         vertical = Input.GetAxis("Vertical"); 
         if(Mathf.Abs(horizontal) == 0 && Mathf.Abs(vertical) == 0) { 
               timer = 0.0; 
         } 
         else
         { 
                waveslice = Mathf.Sin(timer); 
                timer = timer + bobSpeed; 
                if(timer > Mathf.PI * 2)
                { 
                   timer = timer - (Mathf.PI * 2); 
                } 
         } 
         if(waveslice != 0)
         { 
                translateChange = waveslice * bobAmount; 
                totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical); 
                totalAxes = Mathf.Clamp (totalAxes, 0.0, 1.0); 
                translateChange = totalAxes * translateChange; 
                mainCam.transform.localPosition.y = smoothHeight.y + translateChange; 
         } 
         else
         { 
            mainCam.transform.localPosition.y = smoothHeight.y; 
         } 
     }
     else
     {
         //Old animation stuff, not needed
         //animObject.animation.CrossFade("Idle");
         animator.SetBool("idle", true);
         bobSpeed = 0;
         bobAmount = 0;
     }
     moveDirection.y -= gravity * Time.deltaTime;
     if(hitCeiling)
     {
         moveDirection.y -= gravity * Time.deltaTime;
     }
     var flags = controller.Move(moveDirection * Time.deltaTime);
     hitCeiling = ((flags & CollisionFlags.CollidedAbove) != 0);
     if(energy > maxEnergy)
     {
         energy = maxEnergy;
     }
 }
 
 function Run()
 {
     moveSpeed = runSpeed;
     energy -= energyRegenRate * Time.deltaTime;
     running = true;
 }
 
 function Jump()
 {
     moveDirection.y = jumpSpeed;
     //Old animation stuff, not needed
     //fallAnimGO.animation.CrossFadeQueued("Jump", 0.1, QueueMode.PlayNow);
 }
 
 function OnControllerColliderHit(Hit : ControllerColliderHit)
 {
     if(!controller.isGrounded && controller.velocity.y < -6)
     {
         //Old animation stuff, not needed    
         //fallAnimGO.animation.CrossFadeQueued("Fall", 0.3, QueueMode.PlayNow);
     }
 }
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fanttum · Oct 22, 2014 at 07:33 PM 1
Share

I didn't really read all that code, so I'll just make this a comment, but a good way is to pass your variables into mecanim. For example:

     anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);

     anim.SetFloat ("Speed", someFloat); 

If you put these variables in your anim controller, then set transitions to act on these variables.

Like in my example vSpeed is for vertical speed, and thus used for jumping. if vSpeed > 0, then transition to the jump animation. If vSpeed < 0, then go to a falling animation.

$$anonymous$$oving with speed will depend on how you move, but once you get your speed you could say in mecanim that once Speed is > 0 then walk, then once Speed > 0.5 use a run animation.

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

27 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

User Created Animations Not Working With Mecanim 0 Answers

Why isn't my animation being played? 0 Answers

How to properly place a rifle weapon into the Character's hands and change pose? 0 Answers

Is it possible to create new humanoid clips within Unity? 2 Answers

How to use/apply multiple animations correctly? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges