using UnityEngine; namespace AnimatorPlus.Example { public class CharacterControllerExample : MonoBehaviour { public global::AnimatorPlus.AnimatorPlus animatorPlus; public bool IsRootMotion = true; public bool NotPlayingClipUntilLastAnimFinished = true; [Header("Character Movement")] [Range(0,2)]public float MoveSpeed = 1.6f; [Range(0,20)]public float RotSpeed = 10; [Header("Play Anim When Click Left Mouse Button,Cancel When Right Mouse Button")] public AnimationClip AnimationClip; public float fadeInTime = 0.2f; public float fadeOutTime = 0.2f; private float animClipPlayTimer; private void Start() { animatorPlus = GetComponentInChildren(); } private void Update() { animatorPlus.IsRootMotion = IsRootMotion; if (IsRootMotion) { UpdateRootMotion(); } else { UpdateInPlace(); } } void UpdateRootMotion() { if (animatorPlus.AnimatorPlayWeight > 0.1f)// not accept move input during animClip is playing { //Move the character float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); var inputMove = new Vector3(h, 0, v); //Turn the character if (inputMove.magnitude > 0) transform.forward = Vector3.RotateTowards(transform.forward, inputMove.normalized, Time.deltaTime * RotSpeed, 0); animatorPlus.Animator.SetFloat("Speed", inputMove.magnitude * MoveSpeed); } if (Input.GetMouseButton(0)) { if (!NotPlayingClipUntilLastAnimFinished || animClipPlayTimer < Time.time) { animatorPlus.PlayAnimationClip(AnimationClip, fadeInTime, fadeOutTime); animClipPlayTimer = Time.time + AnimationClip.length - fadeOutTime; } } else if (Input.GetMouseButton(1)) { animatorPlus.PlayAnimator(fadeOutTime); if(NotPlayingClipUntilLastAnimFinished) animClipPlayTimer = 0; } //If using root motion, update the position based on the delta position from the animatorPlus transform.position += animatorPlus.DeltaPosition; transform.rotation *= animatorPlus.DeltaRotation; } void UpdateInPlace() { if (animatorPlus.AnimatorPlayWeight > 0.1f) // not accept move input during animClip is playing { //Move the character float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); var inputMove = new Vector3(h, 0, v); //Turn the character if (inputMove.magnitude > 0) transform.forward = Vector3.RotateTowards(transform.forward, inputMove.normalized, Time.deltaTime * RotSpeed, 0); //If not using root motion, update the position based on the input vector transform.position += (inputMove.magnitude > 0.2f? 1:0 ) * Time.deltaTime * MoveSpeed * transform.forward; animatorPlus.Animator.SetFloat("Speed", inputMove.magnitude * MoveSpeed); } if (Input.GetMouseButton(0)) { if (!NotPlayingClipUntilLastAnimFinished || animClipPlayTimer < Time.time) { animatorPlus.PlayAnimationClip(AnimationClip, fadeInTime, fadeOutTime); animClipPlayTimer = Time.time + AnimationClip.length - fadeOutTime; } } else if (Input.GetMouseButton(1)) { animatorPlus.PlayAnimator(fadeOutTime); if(NotPlayingClipUntilLastAnimFinished) animClipPlayTimer = 0; } } } }