# 3. Look-At Interest Targets and Aim Chains Part of [[Procedural Animation and IK]]. Previous: [[2. Foot IK and Ground Alignment]]. Next: [[4. Procedural Stepping and Secondary Motion]]. > [!warning] Code not compiled > Written against the Animation Rigging 1.4 API (`MultiAimConstraint`, `Rig.weight`) and the 6000.5 Scripting Reference. Not compiled or play-tested. [[6.Worked Example Locomotion Look-At and Hand IK]] aims a head at one hand-placed target. Real characters need to **decide what to look at**: the player who just walked in, the door that slammed, the item on the table. This part separates the decision (a director) from the motion (a rig). ## 3.1 One proxy target, many interests The key design choice: **every MultiAim constraint aims at one `LookProxy` transform**, and script moves that proxy. You never edit a constraint's source list at runtime. Why: `sourceObjects` is baked into the rig's animation jobs when the `RigBuilder` builds. Changing it at runtime means calling `RigBuilder.Build()` again, which rebuilds the PlayableGraph (and is what the "Scripted MultiAim sources" note in [[5.Animation Rigging and Script IK]] warns about). Moving a transform is free, and smoothing it gives you natural head turns for nothing. ``` Character ├── Model (Animator, RigBuilder) │ ├── Armature ... │ └── Rig_Look (Rig) <- RigBuilder layer; LookAtDirector fades Rig.weight │ ├── Aim_Chest MultiAimConstraint weight 0.3 limits -30..30 source: LookProxy │ ├── Aim_Neck MultiAimConstraint weight 0.5 limits -40..40 source: LookProxy │ └── Aim_Head MultiAimConstraint weight 1.0 limits -60..60 source: LookProxy └── LookProxy (empty, NOT under the armature) ``` ## 3.2 Build the aim chain 1. Under `Model`, create `Rig_Look`, add **Rig**, add it to **Rig Builder > Rig Layers** (above or below `Rig_Feet` from part 2; constraints only touch different bones, so order does not matter here). 2. Create `LookProxy` as a child of the **character root** (not the armature) at eye height, 2 m in front. 3. Add three children with **Multi-Aim Constraint**. For each: - **Constrained Object:** Chest (or UpperChest/Spine2), Neck, Head. Use the Bone Renderer to find them. - **Source Objects:** `LookProxy`, weight 1. - **Aim Axis / Up Axis:** the bone's local axes that point forward and up. On Mixamo rigs this is usually **Z** and **Y**; check by selecting the bone with the move tool in Local mode. - **Constrained Axes:** X and Y only for the chest (no roll); X, Y for neck; X, Y, Z for head if you like a slight tilt. - **Min/Max Limit:** the table above. - **Maintain Offset:** off. 4. Set constraint **Weight**: 0.3, 0.5, 1.0. Constraints evaluate in hierarchy order, so the chest turns a bit, the neck turns more, and the head finishes the job. This spreads the turn over the spine like a real body. Test in Play Mode by dragging `LookProxy` around: the head should lead, and the chest should follow a little. ## 3.3 LookAtInterest.cs ```csharp using System.Collections.Generic; using UnityEngine; /// <summary> /// Something worth looking at. Registers itself in a static list while enabled, /// so directors never search the scene. Ping() adds a temporary priority boost /// (a noise, a flash, a door slam). Not compiled in an editor. /// </summary> public sealed class LookAtInterest : MonoBehaviour { static readonly List<LookAtInterest> active = new(); public static IReadOnlyList<LookAtInterest> Active => active; [Tooltip("Optional point to look at, e.g. a face bone. Defaults to this transform.")] [SerializeField] Transform lookPoint; [SerializeField, Min(0f)] float basePriority = 1f; [SerializeField, Min(0.1f)] float range = 8f; float boost; float boostUntil; public Vector3 Point => lookPoint != null ? lookPoint.position : transform.position; public float Range => range; public float Priority => basePriority + (Time.time < boostUntil ? boost : 0f); /// <summary>Temporarily raise priority, e.g. when this object makes a noise.</summary> public void Ping(float extraPriority, float seconds) { boost = Mathf.Max(Time.time < boostUntil ? boost : 0f, extraPriority); boostUntil = Mathf.Max(boostUntil, Time.time + seconds); } void OnEnable() => active.Add(this); void OnDisable() => active.Remove(this); } ``` ## 3.4 LookAtDirector.cs ```csharp using UnityEngine; using UnityEngine.Animations.Rigging; /// <summary> /// Chooses the best LookAtInterest and moves a single proxy target that all /// MultiAim constraints aim at. Fades the look rig out when nothing is interesting /// or the target is behind the character. Not compiled in an editor. /// </summary> public sealed class LookAtDirector : MonoBehaviour { [SerializeField] Animator animator; [Tooltip("Eye reference. If empty, uses the Humanoid head bone.")] [SerializeField] Transform eyes; [SerializeField] Transform lookProxy; [SerializeField] Rig lookRig; [Header("Selection")] [SerializeField, Range(10f, 360f)] float fieldOfView = 200f; [SerializeField] float retargetInterval = 0.25f; [Tooltip("Current target's score is multiplied by 1 + this, to stop flicking between two targets.")] [SerializeField] float stickiness = 0.25f; [SerializeField] LayerMask lineOfSightBlockers = 0; [Header("Motion")] [SerializeField] float proxySmoothTime = 0.18f; [SerializeField] float weightSharpness = 6f; [SerializeField] float idleDistance = 2f; LookAtInterest current; LookAtInterest forced; float forcedUntil; float nextEval; Vector3 proxyVelocity; public LookAtInterest Current => current; void Awake() { if (eyes == null && animator != null && animator.isHuman) eyes = animator.GetBoneTransform(HumanBodyBones.Head); if (eyes == null) eyes = transform; } /// <summary>Look at a specific interest for a while (cutscene beat, dialogue line).</summary> public void Force(LookAtInterest interest, float seconds) { forced = interest; forcedUntil = Time.time + seconds; nextEval = 0f; } void Update() { if (Time.time >= nextEval) { nextEval = Time.time + retargetInterval; current = (forced != null && Time.time < forcedUntil) ? forced : Choose(); } Vector3 idlePoint = eyes.position + transform.forward * idleDistance; Vector3 goal = current != null ? current.Point : idlePoint; lookProxy.position = Vector3.SmoothDamp(lookProxy.position, goal, ref proxyVelocity, proxySmoothTime); float wanted = current != null && InView(lookProxy.position) ? 1f : 0f; lookRig.weight = Mathf.Lerp(lookRig.weight, wanted, 1f - Mathf.Exp(-weightSharpness * Time.deltaTime)); } LookAtInterest Choose() { LookAtInterest best = null; float bestScore = 0f; var list = LookAtInterest.Active; for (int i = 0; i < list.Count; i++) { LookAtInterest it = list[i]; if (it == null || it.transform.IsChildOf(transform)) continue; // never look at yourself Vector3 to = it.Point - eyes.position; float dist = to.magnitude; if (dist > it.Range || dist < 0.05f) continue; if (!InView(it.Point)) continue; if (lineOfSightBlockers != 0 && Physics.Raycast(eyes.position, to / dist, dist - 0.1f, lineOfSightBlockers, QueryTriggerInteraction.Ignore)) continue; float distanceFactor = 1f - dist / it.Range; // closer is better float angle = Vector3.Angle(transform.forward, to); float angleFactor = Mathf.Lerp(1f, 0.4f, angle / (fieldOfView * 0.5f)); // in front is better float score = it.Priority * distanceFactor * angleFactor; if (it == current) score *= 1f + stickiness; if (score > bestScore) { bestScore = score; best = it; } } return best; } bool InView(Vector3 point) { Vector3 flat = Vector3.ProjectOnPlane(point - eyes.position, Vector3.up); if (flat.sqrMagnitude < 0.0001f) return true; return Vector3.Angle(transform.forward, flat) <= fieldOfView * 0.5f; } } ``` ### Design notes - **Evaluate a few times a second, move every frame.** Choosing at 4 Hz is cheap and looks more natural than re-choosing every frame; the `SmoothDamp` proxy hides the discrete choice. - **Stickiness is hysteresis.** Without it, two equal targets make the head ping-pong. - **Fade the whole rig, not the constraints.** `Rig.weight` scales every constraint under it, so the chain keeps its 0.3/0.5/1.0 proportions while fading. - **Field of view of 200 degrees** lets a character glance slightly behind the shoulder; past that, the limits on the constraints would clamp anyway and the pose looks broken, so fading is better. ## 3.5 Sensing bridge: look at what you heard [[Organic Enemy Sensing]] produces "I heard something at position P". This bridge turns that into a look target without coupling the two systems: give your sensing component a UnityEvent or C# event with a `Vector3`, and point it at `OnNoiseHeard`. ```csharp using UnityEngine; /// <summary> /// Moves a dedicated LookAtInterest to the last heard noise and boosts it, /// so the LookAtDirector turns the head toward the sound. Not compiled in an editor. /// </summary> public sealed class NoiseLookBridge : MonoBehaviour { [Tooltip("A LookAtInterest that is NOT parented to this character.")] [SerializeField] LookAtInterest noiseInterest; [SerializeField] float boostPriority = 5f; [SerializeField] float boostSeconds = 2.5f; void Awake() { if (noiseInterest != null) noiseInterest.transform.SetParent(null, true); } /// <summary>Call from your sensing component when a noise is detected.</summary> public void OnNoiseHeard(Vector3 worldPosition) { if (noiseInterest == null) return; noiseInterest.transform.position = worldPosition; noiseInterest.Ping(boostPriority, boostSeconds); } } ``` This is the Level Up! **telegraph** from Level 11: the head turns toward the noise a beat before the guard walks there, so the player sees the consequence of their noise. ## 3.6 Check - [ ] With no interests in range, the rig weight fades to 0 and the head returns to the animation. - [ ] Two interests at equal distance: the head does not flick between them. - [ ] Walk behind the character: the head turns to about 100 degrees, then lets go. - [ ] Throw a noise: the head turns before the body does. ## Sources - `MultiAimConstraintData` (1.4): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Animations.Rigging.MultiAimConstraintData.html - `WeightedTransformArray` (1.4): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Animations.Rigging.WeightedTransformArray.html - `RigBuilder` (1.4): https://docs.unity3d.com/Packages/[email protected]/api/UnityEngine.Animations.Rigging.RigBuilder.html - `Animator.GetBoneTransform` (6000.5): https://docs.unity.com/en-us/engine/6000.5/script-reference/unityengine/animator/getbonetransform