### Manual Controller State Creation Example Source: https://kybernetik.com.au/animancer/docs/manual/animator-controllers/controller-states Shows how to manually create and play a ControllerState without using a Controller Transition. Includes examples of direct playback, cross-fading, parameter setting, and playing separate animations. ```csharp using UnityEngine; using Animancer; public class ControllerStateExample : MonoBehaviour { [SerializeField] private AnimancerComponent _Animancer; [SerializeField] private RuntimeAnimatorController _Controller; [SerializeField] private AnimationClip _SeparateAnimation; private ControllerState _ControllerState; void ControllerStateExample() { // Create the ControllerState: _ControllerState = new ControllerState(_Controller); // Play it: _Animancer.Play(_ControllerState); // Fade to it over 0.25 seconds: _Animancer.Play(_ControllerState, 0.25f); // Set the "MoveSpeed" parameter in the Animator Controller: _ControllerState.SetFloat("MoveSpeed", 0.5f); // Play a separate animation not included in the Animator Controller: _Animancer.Play(_SeparateAnimation); } } ``` -------------------------------- ### LinearMixerState Example Script Source: https://kybernetik.com.au/animancer/docs/manual/blending/mixers/creation A complete example demonstrating the manual creation of a LinearMixerState, playing it, and controlling its blend parameter based on a slider. It also shows how to prevent synchronization for specific child states. ```csharp using Animancer; using UnityEngine; public class LinearMixerExample : MonoBehaviour { [SerializeField] private AnimancerComponent _Animancer; [SerializeField] private AnimationClip _Idle; [SerializeField] private AnimationClip _Walk; [SerializeField] private AnimationClip _Run; [SerializeField, Range(0, 1)] private float _MovementSpeed; // Keep the mixer after it's created so we can change the Parameter later. private LinearMixerState _MovementMixer; protected virtual void Awake() { // Make a new mixer and add children to it using a Collection Initializer. _MovementMixer = new LinearMixerState { { _Idle, 0 }, { _Walk, 0.5f }, { _Run, 1 }, }; // Don't synchronize the Idle animation (Index 0) with the Walk and Run cycles. _MovementMixer.DontSynchronize(_MovementMixer.GetChild(0)); // Then you can Play the mixer just like a regular clip. _Animancer.Play(_MovementMixer); } protected virtual void Update() { // Set the mixer's parameter to control its current blending. _MovementMixer.Parameter = _MovementSpeed; } } ``` -------------------------------- ### Transition Asset Example Source: https://kybernetik.com.au/animancer/docs/manual/transitions/assets Shows how to use a TransitionAsset, which must be created separately and referenced in the Inspector. ```csharp using Animancer; using UnityEngine; public class AssetExample : MonoBehaviour { [SerializeField] private TransitionAsset _Animation; } ``` -------------------------------- ### Play Animation and Start Custom Easing - C# Source: https://kybernetik.com.au/animancer/docs/manual/blending/fading/custom Play an animation and then set a custom easing function for its fade group. This example shows how to start a fade and then apply a custom easing function. ```csharp void EasingExample(AnimancerComponent animancer, AnimationClip clip) { AnimancerState state = animancer.Play(clip, 0.25f); ``` -------------------------------- ### Create Transition Asset in Code Source: https://kybernetik.com.au/animancer/docs/manual/transitions/assets Example of creating a TransitionAsset programmatically using ScriptableObject.CreateInstance. ```csharp ScriptableObject.CreateInstance() ``` -------------------------------- ### Inline Transition Example Source: https://kybernetik.com.au/animancer/docs/manual/transitions/assets Demonstrates an inline transition using ITransition, allowing configuration directly in the Inspector. ```csharp using Animancer; using UnityEngine; public class InlineExample : MonoBehaviour { [SerializeReference] private ITransition _Animation; } ``` -------------------------------- ### Specific Inline Transition Example Source: https://kybernetik.com.au/animancer/docs/manual/transitions/assets An inline transition example specifying ClipTransition directly, avoiding the Inspector dropdown for type selection. ```csharp using Animancer; using UnityEngine; public class InlineExample : MonoBehaviour { [SerializeField] private ClipTransition _Animation; } ``` -------------------------------- ### Play Controller Transition Example Source: https://kybernetik.com.au/animancer/docs/manual/animator-controllers/controller-states Demonstrates playing an Animator Controller via a Controller Transition and setting its parameters. Also shows playing a separate animation. ```csharp using UnityEngine; public class ControllerTransitionExample : MonoBehaviour { [SerializeField] private AnimancerComponent _Animancer; [SerializeField] private ControllerTransition _Controller; [SerializeField] private AnimationClip _SeparateAnimation; void ControllerTransitionExample() { // Play the Animator Controller: _Animancer.Play(_Controller); // Set the "MoveSpeed" parameter in the Animator Controller: _Controller.State.SetFloat("MoveSpeed", 0.5f); // Play a separate animation not included in the Animator Controller: _Animancer.Play(_SeparateAnimation); } } ``` -------------------------------- ### Basic FSM Example in C# Source: https://kybernetik.com.au/animancer/docs/manual/fsm Demonstrates initializing and changing states in an Animancer FSM. Use this to see the FSM system in action and observe state transition logs. ```csharp using Animancer.FSM; using UnityEngine; public class StateMachineExample : MonoBehaviour { private LoggerState _Idle = new LoggerState("Idle"); private LoggerState _Walk = new LoggerState("Walk"); private readonly StateMachine StateMachine = new StateMachine(); protected virtual void Awake() { // Start in the Idle state. StateMachine.ForceSetState(_Idle); } protected virtual void Update() { // Swap between the two states whenever the mouse is clicked. if (Input.GetMouseButtonDown(0)) { Debug.Log("Mouse was Clicked"); if (_StateMachine.CurrentState == _Idle) _StateMachine.TrySetState(_Walk); else _StateMachine.TrySetState(_Idle); // Each of those TrySetState calls will check: // CanExitState on the previous state. // CanEnterState on the next state. // Then since they both return true it will change the state and call: // OnExitState on the previous state. // OnEnterState on the next state. // See the Changing States page for more details. } } } public class LoggerState : IState { public readonly string Name; public LoggerState(string name) { Name = name; } public bool CanEnterState { get { Debug.Log("CanEnterState: " + Name); return true; } } public bool CanExitState { get { Debug.Log("CanExitState: " + Name); return true; } } public void OnEnterState() { Debug.Log("OnEnterState: " + Name); } public void OnExitState() { Debug.Log("OnExitState: " + Name); } } ``` -------------------------------- ### Rapid Fire Script with FadeMode.FromStart Source: https://kybernetik.com.au/animancer/docs/samples/basics/transitions This script enhances the previous example by incorporating `FadeMode.FromStart` when playing the action animation. This allows the animation to blend from its beginning on each click, creating a rapid-fire effect. ```csharp using Animancer; using Animancer.Samples; using UnityEngine; public class PlayTransitionOnClick : MonoBehaviour { [SerializeField] private AnimancerComponent _Animancer; [SerializeField] private AnimationClip _Idle; [SerializeField] private AnimationClip _Action; protected virtual void OnEnable() { _Animancer.Play(_Idle, 0.25f); } protected virtual void Update() { if (SampleInput.LeftMouseUp) { AnimancerState state = _Animancer.Play(_Action, 0.25f, FadeMode.FromStart); state.Events(this).OnEnd ??= OnEnable; } } } ``` -------------------------------- ### Initialize LinearMixerState with Collection Initializer Source: https://kybernetik.com.au/animancer/docs/changes/animancer-v7-4 This example shows the streamlined way to initialize a `LinearMixerState` using collection initializers, allowing for concise creation of mixers with multiple child states and their thresholds. ```csharp LinearMixerState mixer = new LinearMixerState { { idle, 0 }, { walk, 0.5f }, { run, 1 }, }; ``` -------------------------------- ### Full Script with ClipTransitions Source: https://kybernetik.com.au/animancer/docs/samples/basics/transitions A complete C# script demonstrating the use of ClipTransitions for managing animations, including setup, event handling, and playback. ```csharp using Animancer; using Animancer.Samples; using UnityEngine; public class PlayTransitionOnClick : MonoBehaviour { [SerializeField] private AnimancerComponent _Animancer; [SerializeField] private ClipTransition _Idle; [SerializeField] private ClipTransition _Action; protected virtual void Awake() { _Action.Events.OnEnd = OnEnable; } protected virtual void OnEnable() { _Animancer.Play(_Idle); } protected virtual void Update() { if (SampleInput.LeftMouseUp) { _Animancer.Play(_Action); } } } ``` -------------------------------- ### Hypothetical JumpState Implementation with Parameters Source: https://kybernetik.com.au/animancer/docs/manual/fsm/changing-states A concrete state implementation demonstrating the hypothetical parameter-based interface. Parameters are present but unused in this example. ```csharp public class JumpState : CharacterState { public override bool CanEnterState(TState previousState) => Character.Body.IsGrounded; public override void OnEnterState(TState previousState) { Character.Rigidbody.AddForce(...); Character.Animancer.Play(...); } } ``` -------------------------------- ### Manual Nesting Example for Animancer Source: https://kybernetik.com.au/animancer/docs/manual/blending/mixers/creation Use this when you want to manually create and configure nested mixer states. This approach provides direct control over state creation and management. ```csharp using Animancer; using UnityEngine; public class ManualNestedMixerExample : MonoBehaviour { [SerializeField] private AnimancerComponent _Animancer; [SerializeField] private MixerTransition2D _RegularMovement; [SerializeField] private MixerTransition2D _InjuredMovement; [SerializeField, Range(0, 1)] private float _InjuryLevel; [SerializeField, Range(-1, 1)] private float _MovementX; [SerializeField, Range(-1, 1)] private float _MovementY; private LinearMixerState _MovementMixer; protected virtual void Awake() { // Add a Child using the Regular Movement transition with a Threshold of 0. // Add a Child using the Injured Movement transition with a Threshold of 1. _MovementMixer = new LinearMixerState { { _RegularMovement, 0 }, { _InjuredMovement, 1 } }; // Optionally give the mixers names to show in the Inspector: _MovementMixer.SetDebugName("Movement"); _RegularMovement.BaseState.SetDebugName("Regular Movement"); _InjuredMovement.BaseState.SetDebugName("Injured Movement"); _Animancer.Play(_MovementMixer); } protected virtual void Update() { // The _MovementMixer.Parameter corresponds to the Thresholds assigned above: // 0 = Regular. // 0.5 = Halfway between Regular and Injured. // 1 = Injured. _MovementMixer.Parameter = _InjuryLevel; // And the child mixer parameters correspond to the current movement direction. Vector2 movement = new Vector2(_MovementX, _MovementY); _RegularMovement.State.Parameter = movement; _InjuredMovement.State.Parameter = movement; } } ``` -------------------------------- ### Obstacle Treadmill Script Setup Source: https://kybernetik.com.au/animancer/docs/samples/ik/uneven-ground Defines fields for the ObstacleTreadmill script, using Unity's attribute system to specify units in the Inspector. ```csharp using System.Collections.Generic; using UnityEngine; public class ObstacleTreadmill : MonoBehaviour { [SerializeField] private float _SpawnCount = 20; [SerializeField] private Material _ObstacleMaterial; [SerializeField, Meters] private float _Length = 6; [SerializeField, Degrees] private float _RotationVariance = 45; [SerializeField, Multiplier] private float _BaseScale = 0.8f; [SerializeField, Multiplier] private float _ScaleVariance = 0.3f; [SerializeField] private Transform _Target; ``` -------------------------------- ### Initialize InputBuffer Source: https://kybernetik.com.au/animancer/docs/samples/fsm/weapons Initialize an InputBuffer with the character's StateMachine to enable buffered state changes. This setup is typically done in the Awake method. ```csharp private StateMachine.InputBuffer _InputBuffer; protected virtual void Awake() { _InputBuffer = new StateMachine.InputBuffer(_Character.StateMachine); } ``` -------------------------------- ### Setup and Insert Two Bone IK Job Source: https://kybernetik.com.au/animancer/docs/samples/jobs/two-bone-ik Initializes the TwoBoneIKJob with the Animator, bone transforms, and target, then inserts it into Animancer's PlayableGraph to process IK calculations each frame. ```csharp TwoBoneIKJob twoBoneIKJob = new TwoBoneIKJob(); twoBoneIKJob.Setup(_Animancer.Animator, topBone, midBone, _EndBone, _Target); _Animancer.Graph.InsertOutputJob(twoBoneIKJob); } ``` -------------------------------- ### Transition Animation Source: https://kybernetik.com.au/animancer/docs/manual/playing These methods allow Transitions to apply all their details in a single call, including fade duration and other configurable properties like Speed, Start Time, and Animancer Events. ```csharp Play(ITransition transition) Play(ITransition transition, float fadeDuration, FadeMode mode = FadeMode.FixedSpeed) ``` -------------------------------- ### Apply Lambda Easing Function - C# Source: https://kybernetik.com.au/animancer/docs/manual/blending/fading/custom Assign a lambda expression as the easing function to modify the fade progress. This example uses a simple lambda to square the progress value, resulting in a slow start and fast end. ```csharp // Assign any function that takes a float and returns a float. state.FadeGroup.SetEasing(t => t * t);// Square the 0-1 value to start slow and end fast. // The Easing class has lots of standard mathematical curve functions. state.FadeGroup.SetEasing(Easing.Sine.InOut); // Or you can use the Easing.Function enum. state.FadeGroup.SetEasing(Easing.Function.SineInOut); } ``` -------------------------------- ### Get AnimancerComponent Source: https://kybernetik.com.au/animancer/docs/samples/fine-control/update-rate This snippet shows how to get a reference to the AnimancerComponent you wish to control. It is typically done via a serialized field in a MonoBehaviour. ```csharp using Animancer; using UnityEngine; public class LowUpdateRate : MonoBehaviour { [SerializeField] private AnimancerComponent _Animancer; ``` -------------------------------- ### Set Animation Start Time (Mecanim) Source: https://kybernetik.com.au/animancer/docs/introduction/mecanim-vs-animancer/comparison/speed-and-time Specify the starting point of an animation in Mecanim using the 'normalizedTime' parameter in Play or CrossFade methods. ```csharp using UnityEngine; public class Example : MonoBehaviour { [SerializeField] Animator _Animator; void SkipToHalfTime() { // State Name, Layer, Normalized Time. _Animator.Play("Action", 0, 0.5f); } } ``` -------------------------------- ### Keyless StateMachine Initialization Source: https://kybernetik.com.au/animancer/docs/manual/fsm/keys Demonstrates initializing a keyless StateMachine with a direct reference to the initial state. This approach requires explicit state references when transitioning. ```csharp public class Character : MonoBehaviour { [SerializeField] private State _Idle; // Need public access to the state. public State Idle => _Idle; public StateMachine FSM { get; private set; } protected virtual void Awake() { // Initialize with the starting state. // It doesn't know about any other // states until they are used. FSM = new StateMachine(_Idle); } } // Empty // space // to // line // up // with // the // other // example // code. public class SomethingElse { public void EnterIdle(Character character) { // We need a direct reference to the // FSM and the state to enter it: character.FSM .TryEnterState(character.Idle); } } ``` -------------------------------- ### Particle Effect Activation via Animancer Event Source: https://kybernetik.com.au/animancer/docs/samples/animator-controllers/3d-game-kit/respawn Activates particle effects at the start of the respawn animation using an Animancer Event. This is a workaround for script referencing issues, ensuring the effect starts when the animation frame is first processed. ```csharp // This code snippet is conceptual and demonstrates where an Animancer Event would be set up in the Inspector. // The actual event would be configured on the animation clip at time 0 to call EllenSpawn.StartEffect(). ``` -------------------------------- ### Manipulating AnimancerState Source: https://kybernetik.com.au/animancer/docs/manual/playing Provides examples of directly manipulating an AnimancerState to control animation playback. ```APIDOC ## Play State ### Description Calling methods on a state will only affect that state and won't stop any others that are playing. These methods aren't useful in most circumstances, but they are available if you need more complex control over things. ### Method Signature `state.Play()` `state.StartFade(float targetAlpha, float fadeDuration)` ### Properties - `state.Speed` - `state.Time` - `state.NormalizedTime` ### Events - `state.Events(this).OnEnd` ``` -------------------------------- ### Equipment Component Initialization Source: https://kybernetik.com.au/animancer/docs/samples/fsm/weapons Initializes the Equipment component by attaching the current weapon on startup. ```csharp public class Equipment : MonoBehaviour { [SerializeField] private Transform _WeaponHolder; [SerializeField] private Weapon _Weapon; public Weapon Weapon { get => _Weapon; set { DetachWeapon(); _Weapon = value; AttachWeapon(); } } protected virtual void Awake() { AttachWeapon(); } ``` -------------------------------- ### Current CharacterState Inheritance Source: https://kybernetik.com.au/animancer/docs/manual/fsm/changing-states Example of a concrete character state inheriting from the current StateBehaviour. ```csharp public abstract class CharacterState : StateBehaviour { ... } ``` -------------------------------- ### Keyed StateMachine Initialization with Enum Keys Source: https://kybernetik.com.au/animancer/docs/manual/fsm/keys Shows how to initialize a keyed StateMachine using an enum for state keys. This allows states to be registered and entered using their keys, useful for serialization. ```csharp public class Character : MonoBehaviour { [SerializeField] private State _Idle; // No accessor needed with these keys. public enum Key { Idle, Walk } public StateMachine FSM { get; private set; } protected virtual void Awake() { // Initialize the StateMachine. FSM = new StateMachine(); // Register the states with their key. // More can be registered later, // but that often defeats the purpose. FSM.Add(Key.Idle, _Idle); // Enter the starting state. FSM.ForceSetState(Key.Idle, _Idle); // Since there's only one state here we // could have just passed it into the // constructor, but the point is to show // the initialization. } } public class SomethingElse { public void EnterIdle(Character character) { // We only need access to the FSM // since we can use the enum key: character.FSM .TryEnterState(Key.Idle); // And we still have the ability to use // direct references if necessary. } } ``` -------------------------------- ### Dynamic Layers Fields Source: https://kybernetik.com.au/animancer/docs/samples/layers/dynamic Fields for a dynamic layered animation setup using `LayeredAnimationManager`. ```csharp [SerializeField] private LayeredAnimationManager _AnimationManager; [SerializeField] private ClipTransition _Idle; [SerializeField] private ClipTransition _Move; [SerializeField] private ClipTransition _Action; ``` -------------------------------- ### Basic Layers Fields Source: https://kybernetik.com.au/animancer/docs/samples/layers/dynamic Fields for a basic layered animation setup using `AnimancerComponent`. ```csharp [SerializeField] private AnimancerComponent _Animancer; [SerializeField] private ClipTransition _Idle; [SerializeField] private ClipTransition _Move; [SerializeField] private ClipTransition _Action; [SerializeField] private AvatarMask _ActionMask; [SerializeField, Seconds] private float _ActionFadeOutDuration = AnimancerGraph.DefaultFadeDuration; ``` -------------------------------- ### Old Initialization Logic Source: https://kybernetik.com.au/animancer/docs/samples/basics/character Previously, the OnEnable method would play the _Idle animation on startup. ```csharp protected virtual void Awake() { _Action.Events.OnEnd = OnEnable; } protected virtual void OnEnable() { _Animancer.Play(_Idle); } ``` -------------------------------- ### Try Play Animation Source: https://kybernetik.com.au/animancer/docs/manual/playing Details on how to attempt to play an animation using a key, which will play an existing state if found. ```APIDOC ## Try Play ### Description Unlike the above methods, these ones use the `key` to find an existing State to play but can't create new ones if they aren't yet registered (trying to do so will return `null`). Once the state is found, they simply call the corresponding Play Immediately or Cross Fade method. ### Method Signature `TryPlay(object key)` `TryPlay(object key, float fadeDuration, FadeMode mode = FadeMode.FixedSpeed)` ### Parameters - `key` (object) - The key to identify the animation state. - `fadeDuration` (float) - Optional. The duration of the fade. - `mode` (FadeMode) - Optional. The fade mode, defaults to `FadeMode.FixedSpeed`. ``` -------------------------------- ### OnEnable and PlayMainAnimation for State Entry Source: https://kybernetik.com.au/animancer/docs/samples/animator-controllers/3d-game-kit/idle Handles the initial setup when the IdleState is entered. It plays the main animation, sets a random delay for the next randomization, and adds a fixed delay to the timer. ```csharp protected virtual void OnEnable() { PlayMainAnimation(); _RandomizeTime += _FirstRandomizeDelay; } private void PlayMainAnimation() { _RandomizeTime = UnityEngine.Random.Range(_MinRandomizeInterval, _MaxRandomizeInterval); Character.Animancer.Play(_MainAnimation); } ``` -------------------------------- ### Basic MonoBehaviour Script Source: https://kybernetik.com.au/animancer/docs/samples/basics/quick-play A minimal Unity script that inherits from MonoBehaviour. This serves as a starting point before adding specific functionality. ```csharp using UnityEngine; public class PlayAnimationOnEnable : MonoBehaviour { } ``` -------------------------------- ### Set Animation Start Time (Animancer) Source: https://kybernetik.com.au/animancer/docs/introduction/mecanim-vs-animancer/comparison/speed-and-time Control the current time or normalized time of an animation directly after playing it with Animancer. ```csharp using UnityEngine; using Animancer; public class Example : MonoBehaviour { [SerializeField] AnimancerComponent _Animancer; [SerializeField] AnimationClip _Clip; void PlayAnimation() { AnimancerState state = _Animancer.Play(_Clip); // Skip 1 second in. state.Time = 1; // Skip halfway through. state.NormalizedTime = 0.5f; // Or do it in one line: _Animancer.Play(_Clip).Time = 1; } } ``` -------------------------------- ### Try Play Animation by Key Source: https://kybernetik.com.au/animancer/docs/manual/playing Unlike the Play methods, these use a key to find an existing state but cannot create new ones. If the state is found, they call the corresponding Play Immediately or Cross Fade method. ```csharp TryPlay(object key) TryPlay(object key, float fadeDuration, FadeMode mode = FadeMode.FixedSpeed) ``` -------------------------------- ### Access Current Animation State Source: https://kybernetik.com.au/animancer/docs/manual/playing/states Retrieves the currently playing animation state. For multi-layer setups, this refers to the base layer. ```csharp var state = animancer.States.Current; ``` -------------------------------- ### Initialize LinearMixerState by Adding Children Source: https://kybernetik.com.au/animancer/docs/changes/animancer-v7-4 This method demonstrates initializing a `LinearMixerState` by adding children one by one using the `Add` method. This approach prevents null children and is flexible for mixers of any size. ```csharp LinearMixerState mixer = new LinearMixerState(); mixer.Add(idle, 0); mixer.Add(walk, 0.5f); mixer.Add(run, 1); ``` -------------------------------- ### New Initialization Logic Source: https://kybernetik.com.au/animancer/docs/samples/basics/character The UpdateMovement method now handles initial animation playback, simplifying Awake. ```csharp protected virtual void Awake() { _Action.Events.OnEnd = UpdateMovement; } ``` -------------------------------- ### Incorrect Update Order Example Source: https://kybernetik.com.au/animancer/docs/samples/basics/character Demonstrates an incorrect ordering of UpdateAction and UpdateMovement within the NotActing state, leading to animation issues. ```csharp case State.NotActing: UpdateAction(); UpdateMovement(); break; ``` -------------------------------- ### Initialize StateMachine.WithDefault in Awake Source: https://kybernetik.com.au/animancer/docs/manual/fsm/initialization Recommended pattern for initializing `StateMachine.WithDefault` in `Awake` when using serialized fields. This ensures the `DefaultState` is set after Unity has deserialized fields. ```csharp public class Character : MonoBehaviour { [SerializeField] private AnimancerComponent _Animancer; public AnimancerComponent Animancer => _Animancer; [SerializeField] private CharacterState _Idle; public readonly StateMachine.WithDefault StateMachine = new(); protected virtual void Awake() { StateMachine.DefaultState = _Idle; } } ``` -------------------------------- ### Renamed Classes and Interfaces (v4.0) Source: https://kybernetik.com.au/animancer/docs/changes/animancer-v4-0 Several classes and interfaces have been renamed for better clarity and descriptiveness. For example, `Serializable` classes are now `Transition`. ```csharp ClipState.Serializable ``` ```csharp IAnimancerTransition ``` ```csharp IAnimancerTransitionDetailed ``` ```csharp FloatControllerState ``` ```csharp Vector2ControllerState ``` ```csharp Vector3ControllerState ``` -------------------------------- ### Implement ProcessRootMotion Source: https://kybernetik.com.au/animancer/docs/samples/jobs/job-states Empty implementation for ProcessRootMotion as root motion is not used in this sample. This method is required by IAnimancerStateJob. ```csharp readonly void IAnimancerStateJob.ProcessRootMotion(AnimationStream stream, double time) { } ``` -------------------------------- ### Get Movement Direction Source: https://kybernetik.com.au/animancer/docs/samples/mixers/directional Calculate the desired movement direction based on mouse input and raycasting. Returns Vector3.zero if the raycast misses. ```csharp protected virtual void Update() { Vector3 movementDirection = GetMovementDirection(); ... ``` ```csharp private Vector3 GetMovementDirection() { ``` ```csharp Ray ray = Camera.main.ScreenPointToRay(SampleInput.MousePosition); ``` ```csharp if (!Physics.Raycast(ray, out RaycastHit raycastHit)) return Vector3.zero; ``` ```csharp Vector3 direction = raycastHit.point - transform.position; ``` ```csharp float squaredDistance = direction.sqrMagnitude; if (squaredDistance <= _StopProximity * _StopProximity) { return Vector3.zero; } ``` ```csharp else { return direction / Mathf.Sqrt(squaredDistance); } } ``` -------------------------------- ### Transition Animation Source: https://kybernetik.com.au/animancer/docs/manual/playing Explains how to play animations using an ITransition object, allowing for configuration of various animation details. ```APIDOC ## Transition ### Description These methods allow Transitions to apply all their details in a single call. This includes the `fadeDuration` as well as any other details defined in the `transition` such as Speed, Start Time, and any Animancer Events. ### Method Signature `Play(ITransition transition)` `Play(ITransition transition, float fadeDuration, FadeMode mode = FadeMode.FixedSpeed)` ### Parameters - `transition` (ITransition) - The transition object containing animation details. - `fadeDuration` (float) - Optional. The duration of the fade. - `mode` (FadeMode) - Optional. The fade mode, defaults to `FadeMode.FixedSpeed`. ``` -------------------------------- ### Get IK Bones Source: https://kybernetik.com.au/animancer/docs/samples/jobs/two-bone-ik Retrieves the necessary bone transforms for the IK calculation. The midBone is the parent of the endBone, and the topBone is the parent of the midBone. ```csharp protected virtual void Awake() { Transform midBone = _EndBone.parent; Transform topBone = midBone.parent; ``` -------------------------------- ### Animancer v3.1 Playback Methods Source: https://kybernetik.com.au/animancer/docs/changes/animancer-v4-0 Illustrates the various overloads for Play, CrossFade, and Transition methods in Animancer v3.1, highlighting their complexity due to default parameters. ```csharp // Old Methods from v3.1: Play(AnimationClip clip, int layerIndex = 0) Play(AnimancerState state) Play(object key) // Note: replaced "DefaultFadeDuration" with just "Default" to fit everything on one line. CrossFade(AnimationClip clip, float fadeDuration = Default, int layerIndex = 0) CrossFade(AnimancerState state, float fadeDuration = Default) CrossFade(object key, float fadeDuration = Default) CrossFadeFromStart(AnimationClip clip, float fadeDuration = Default, int layerIndex = 0) CrossFadeFromStart(AnimancerState state, float fadeDuration = Default, int layerIndex = 0) CrossFadeFromStart(object key, float fadeDuration = Default, int layerIndex = 0) Transition(ITransition transition, int layerIndex = 0) ``` -------------------------------- ### Character State Machine Initialization Source: https://kybernetik.com.au/animancer/docs/samples/fsm/characters Initializes the StateMachine after deserialization using the InitializeAfterDeserialize method. This ensures the state machine is ready before the game starts. ```csharp [DefaultExecutionOrder(-10000)] public class Character : MonoBehaviour { ... [SerializeField] private StateMachine.WithDefault _StateMachine; public StateMachine.WithDefault StateMachine => _StateMachine; protected virtual void Awake() { _StateMachine.InitializeAfterDeserialize(); } } ``` -------------------------------- ### SampleButton Script - AddButton Method Source: https://kybernetik.com.au/animancer/docs/samples/basics/scene-setup Adds a button to the UI, either initializing the current instance or instantiating a clone for subsequent buttons. It handles positioning, click listeners, and text assignment. ```csharp public SampleButton AddButton( int index, string text, UnityAction onClick) { SampleButton button = this; if (index != 0) { button = Instantiate(button, button._Transform.parent); Vector2 position = button._Transform.anchoredPosition; position.y -= index * (button._Transform.sizeDelta.y + button._Spacing); button._Transform.anchoredPosition = position; } button._Button.onClick.AddListener(onClick); button._Text.text = text; button.name = text; return button; } } ``` -------------------------------- ### Configure Raycast Properties Source: https://kybernetik.com.au/animancer/docs/samples/ik/uneven-ground DefineSerializeField variables for raycast origin offset and end position. These control where the ray starts and how far it extends downwards. ```csharp [SerializeField, Meters] private float _RaycastOriginY = 0.5f; [SerializeField, Meters] private float _RaycastEndY = -0.2f; ``` -------------------------------- ### Play Animation from Start with Fade Mode Source: https://kybernetik.com.au/animancer/docs/samples/basics/transitions Use `FadeMode.FromStart` as the third parameter in the `Play` method to ensure the animation always fades in from its beginning, even if it's already playing. This is useful for rapid playback or blending into an animation that is already in progress. ```csharp AnimancerState state = _Animancer.Play( _Action, 0.25f, FadeMode.FromStart); state.Time = 0; ``` -------------------------------- ### Clip Transitions (New) Source: https://kybernetik.com.au/animancer/docs/samples/basics/transitions Defines fields for ClipTransitions, which encapsulate AnimationClips with additional playback settings like fade duration and start time. ```csharp using Animancer; using UnityEngine; public class Example : MonoBehaviour { [SerializeField] private AnimancerComponent _Animancer; [SerializeField] private ClipTransition _Idle; [SerializeField] private ClipTransition _Action; } ``` -------------------------------- ### Simplifying State Transitions with IOwnedState Source: https://kybernetik.com.au/animancer/docs/manual/fsm/utilities/owned-states With IOwnedState, you can use extension methods like TryEnterState() on the state itself, rather than calling TrySetState() on the state machine. This also applies to checking the current state with IsCurrentState(). ```csharp public class CharacterBrain : MonoBehaviour { [SerializeField] private Character _Character; [SerializeField] private CharacterState _Walk; protected virtual void Update() { if (Input.GetKey(KeyCode.W)) { // Normally we would need to tell the StateMachine which state to enter. _Character.StateMachine.TrySetState(_Walk); // But since CharacterState implements IOwnedState we can do the same thing with: _Walk.TryEnterState(); } } private bool IsWalking() { // Without IOwnedState: return _Character.StateMachine.CurrentState == _Walk; // With IOwnedState: return _Walk.IsCurrentState(); } } ``` -------------------------------- ### Constructing and Using InputBuffer Source: https://kybernetik.com.au/animancer/docs/manual/fsm/utilities/input-buffer Instantiate an InputBuffer with your state machine. Use Buffer() to queue state changes and Update() each frame to process them. ```csharp var buffer = new StateMachine.InputBuffer(myStateMachine); // Instead of myStateMachine.TryResetState(MyStates.Attack) buffer.Buffer(MyStates.Attack, 0.5f); // Call every frame buffer.Update(Time.deltaTime); ```