using System.Collections.Generic; using UnityEngine; namespace GrassCutter { /// /// The small life of things standing about: a dish panning slowly over the sky, a windsock or a whip aerial swaying (more /// in a wind), a sensor turning, robot eyes blinking now and then. Parts are found by the names the models give them /// (Dish, Sway*, SpinSensor, Blink*); anything another script already drives is left to it. /// public class IdleMotion : MonoBehaviour { struct Part { public Transform t; public int kind; // 0 dish, 1 sway, 2 spin, 3 blink public Vector3 axis, scale; public float phase; } readonly List _parts = new List(); float _blinkAt; /// Adds the motion to whatever under root has parts for it; nothing if there are none. public static void Attach(GameObject root) { if (root && !root.GetComponent()) root.AddComponent(); } void Start() { // a mowbot looks after its own spinning, swaying and blinking bool bot = GetComponentInChildren(true); var up = transform.up; foreach (var t in GetComponentsInChildren(true)) { var n = t.name; int kind = n == "Dish" ? 0 : n.StartsWith("Sway") ? 1 : n == "SpinSensor" ? 2 : n.StartsWith("Blink") ? 3 : -1; if (kind < 0 || (bot && kind != 0)) continue; int ax = BaseRot.LocalAxisFor(t, kind == 1 ? transform.right : up); var axis = ax == 0 ? Vector3.right : ax == 1 ? Vector3.up : Vector3.forward; BaseRot.Of(t); _parts.Add(new Part { t = t, kind = kind, axis = axis, scale = t.localScale, phase = Random.value * 20f }); } if (_parts.Count == 0) { enabled = false; return; } _blinkAt = Time.time + Random.Range(2f, 6f); } void LateUpdate() { float time = Time.time; float wind = WeatherFx.Wind; bool blink = false; if (time >= _blinkAt) { blink = time < _blinkAt + 0.14f; if (!blink) _blinkAt = time + Random.Range(2.5f, 7f); } foreach (var p in _parts) { if (!p.t) continue; switch (p.kind) { case 0: // a slow look round the sky, resting a while at each end float pan = Mathf.SmoothStep(-1f, 1f, Mathf.PingPong((time + p.phase) / 9f, 1f)) * 22f; p.t.localRotation = BaseRot.Of(p.t) * Quaternion.AngleAxis(pan, p.axis); break; case 1: float a = (Mathf.Sin(time * 1.7f + p.phase) * 0.6f + Mathf.Sin(time * 2.9f + p.phase * 1.3f) * 0.4f) * (3f + wind * 14f); p.t.localRotation = BaseRot.Of(p.t) * Quaternion.AngleAxis(a, p.axis); break; case 2: p.t.localRotation = BaseRot.Of(p.t) * Quaternion.AngleAxis((time + p.phase) * 45f, p.axis); break; case 3: p.t.localScale = blink ? Vector3.Scale(p.scale, Vector3.one - p.axis * 0.85f) : p.scale; break; } } } } }