Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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 Hacker69 · Feb 17, 2019 at 06:13 AM · c#animationrigidbodycharactercontrollercapsulecollider

Having problems with animation and character controller velocity not matching

The animation has root motion applied, and the error that i'm getting is that the speed of the capsule collider does not match the speed of the character animation and offsets it hence messing up the camera view and other things. Here is the video for you to see what i'm talking about - https://youtu.be/kU8Dm5bDJXg.

This is the code im using to give velocity to the capsule collider to be the same as the animation.

[code=CSharp]using System.Collections; using System.Collections.Generic; using UnityEngine;

namespace SA { public class AnimatorHook : MonoBehaviour { Animator anim; StateManager states;

     public void Init(StateManager st)
     {
         states = st;
         anim = st.anim;
     }      

     void OnAnimatorMove()
     {
         if (!states.canMove)
             anim.ApplyBuiltinRootMotion();

         states.rigid.drag = 0;
         float multiplier = 1;

         Vector3 delta = anim.deltaPosition;
         delta.y = 0;           
         Vector3 v = (delta * multiplier) / states.delta;
         states.rigid.velocity = v;
     }


 }

} [/code]

This is the main code for applying root motion and handling various other stuff :-

[code=CSharp]using System.Collections; using System.Collections.Generic; using UnityEngine;

namespace SA {

 public class StateManager : MonoBehaviour
 {
     [Header("Init")]
     public GameObject activeModel;

     [Header("Inputs")]
     public float vertical;
     public float horizontal;
     public float moveAmount;
     public Vector3 moveDir;
     public bool rt, rb, lt, lb;

     [Header("Stats")]
     public float moveSpeed = 5f;
     public float runSpeed = 8f;
     public float rotateSpeed = 20;
     public float toGround = 0.5f;

     [Header("States")]
     public bool onGround;
     public bool run;
     public bool lockOn;
     public bool inAction;
     public bool canMove;

     [Header("Other")]
     public EnemyTarget lockOnTarget;

     [HideInInspector]
     public Animator anim;

     [HideInInspector]
     public Rigidbody rigid;
     [HideInInspector]
     public AnimatorHook a_hook;

     [HideInInspector]
     public float delta;
     [HideInInspector]
     public LayerMask ignoreLayers;

     float _actionDelay;

     public void Init()
     {
         SetupAnimator();
         rigid = GetComponent<Rigidbody>();
         rigid.angularDrag = 999;
         rigid.drag = 4;
         rigid.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;

         a_hook = activeModel.AddComponent<AnimatorHook>();
         a_hook.Init(this);

         gameObject.layer = 8;
         ignoreLayers = ~(1 << 9);

         anim.SetBool("onGround",true);
     }

     void SetupAnimator()
     {           
         if(activeModel == null)
         {
             anim = GetComponentInChildren<Animator>();
             if(anim == null)
             {
                 Debug.Log("no model found");
             }
             else
             {
                 activeModel = anim.gameObject;
             }
         }
         if(anim == null)
         {
             anim = activeModel.GetComponent<Animator>();
         }
         //anim.applyRootMotion = false;
     }

     public void FixedTick(float d)
     {
         delta = d;
         rigid.drag = (moveAmount > 0 || !onGround) ? 0 : 4;

         DetectAction();

         if (inAction)
         {
             // anim.applyRootMotion = true;

             _actionDelay += delta;
             if(_actionDelay > 0.3f)
             {
                 inAction = false;
                 _actionDelay = 0;
             }
             else
             {
                 return;
             }
         }

         canMove = anim.GetBool("canMove");

         if (!canMove)
         {
             return;
         }
         //anim.applyRootMotion = false;
        

         float targetSpeed = moveSpeed;

         if (run)
             targetSpeed = runSpeed;            
        

         if(onGround)
             rigid.velocity = moveDir * (targetSpeed * moveAmount);

        /* if (run)
             lockOn = false;
             */

         Vector3 targetDir = (lockOn == false) ? moveDir : lockOnTarget.transform.position - transform.position;
         targetDir.y = 0;
         if (targetDir == Vector3.zero)
             targetDir = transform.forward;
         Quaternion tr = Quaternion.LookRotation(targetDir);
         Quaternion targetRotation = Quaternion.Slerp(transform.rotation, tr, delta * moveAmount * rotateSpeed);
         transform.rotation = targetRotation;

         anim.SetBool("lockon", lockOn);

         if (lockOn == false)
             HandleMovementAnimations();
         else
             HandleLockOnAnimations(moveDir);
     }

     public void DetectAction()
     {
         if (canMove == false)
             return;

         if (rb == false && rt == false && lt == false && lb == false)
             return;

         string targetAnim = null;

         if (rb)
             targetAnim = "Sword And Shield Attack";
         if (rt)
             targetAnim = "Stable Sword Outward Slash";
         if (lb)
             targetAnim = "Standing Melee Attack Horizontal";
         if (lt)
             targetAnim = "Sword And Shield Slash (1)";

         if (string.IsNullOrEmpty(targetAnim))
             return;

         canMove = false;
         inAction = true;
         anim.CrossFade(targetAnim,0.2f);
         //rigid.velocity = Vector3.zero;
     }

     public void Tick(float d)
     {
         delta = d;
         onGround = OnGround();

         anim.SetBool("onGround", onGround);
     }

     void HandleMovementAnimations()
     {
         anim.SetBool("run", run);
         anim.SetFloat("Vertical", moveAmount ,0.4f,delta);
     }

     void HandleLockOnAnimations(Vector3 moveDir)
     {
         Vector3 relativeDir = transform.InverseTransformDirection(moveDir);
         float h = relativeDir.x;
         float v = relativeDir.z;

         anim.SetFloat("Vertical", v, 0.2f, delta);
         anim.SetFloat("Horizontal", h, 0.2f, delta);


     }

     public bool OnGround()
     {
         bool r = false;
         Vector3 origin = transform.position + (Vector3.up * toGround);
         Vector3 dir = -Vector3.up;
         float dis = toGround + 0.3f;
         RaycastHit hit;
         if(Physics.Raycast(origin,dir,out hit,dis))
         {
             r = true;
             Vector3 targetPosition = hit.point;
             transform.position = targetPosition;
         }
         return r;
     }
 }

} [/code]

These are the two main pieces of code that control the character. The other two pieces of could basically take input and controll the camera thats it, so i didnt think it would be necessary for me to upload those codes

Comment
Add comment
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

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.

Follow this Question

Answers Answers and Comments

288 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 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 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 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 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 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 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 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 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 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 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

When jump my character controller model it goes out of collider 0 Answers

Question about pushing objects, "Animate Physics" and Rigidbodies 0 Answers

Quaternion issue: how can I fix this? 0 Answers

Speed up with Rigidbody as frame rate increases c# 1 Answer

Instantiated Bullet Lags Behind Animated Timeline Object 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