using UnityEngine; using System.Collections; /// /// This component is responsible for wobbling a UI element. It will wobble smoothly using /// perlin noise around its original position. It will also stretch and squash. /// public class WobbleAnim : MonoBehaviour { Vector3 _originalPosition; float _noiseX, _noiseY; const float MAX_DISPLACEMENT = 20; const float NOISE_SPEED = 0.7f; const float Y_OFFSET = 100; public UIElementTransition elementTransition; bool isWobbling; void Awake() { if (elementTransition == null) { elementTransition = GetComponent(); } AVDebug.Assert(elementTransition != null, "WobbleAnim is assumed to be on a UI element which is transitioned. UIElementTransition component not found on "+name); elementTransition.OnHiding += OnHiding; elementTransition.OnShowComplete += OnShowComplete; enabled = false; _originalPosition = transform.localPosition; _noiseY = Random.value * 300; //just some random value } void OnDestroy() { if (elementTransition != null) { elementTransition.OnHiding -= OnHiding; elementTransition.OnShowComplete -= OnShowComplete; } } void Start() { iTween.ScaleTo(gameObject, iTween.Hash( "islocal", true, "time", Random.Range(0.5f, 0.8f), //make the time random so they don't look wobbling the same "y", 0.95f * transform.localScale.y, "x", 1.05f * transform.localScale.x, "easetype", iTween.EaseType.easeInOutSine, "looptype", iTween.LoopType.pingPong)); } void Update() { if (isWobbling) { transform.localPosition = GetNextWobblyPosition(); } } void OnHiding() { enabled = false; isWobbling = false; } void OnShowComplete() { enabled = true; //tween to the first wobbly position to avoid a glitch between original position and the first wobbly position iTween.ValueTo(gameObject, iTween.Hash( "from", 0, "to", 1.0f, "time", 0.8f, "easetype", iTween.EaseType.linear, "onupdate", "OniTweenTransitToWobbling", "onupdatetarget", gameObject)); } Vector3 GetNextWobblyPosition() { _noiseX += NOISE_SPEED * Time.deltaTime; float x = Mathf.PerlinNoise(_noiseX, _noiseY) - 0.5f; //note that perlin noise is between 0 and 1... shiftin so it's between -0.5 to 0.5 float y = Mathf.PerlinNoise(_noiseX, _noiseY + Y_OFFSET) - 0.5f; return _originalPosition + new Vector3(x * MAX_DISPLACEMENT, y * MAX_DISPLACEMENT); } void OniTweenTransitToWobbling(float f) { if (f == 1) { isWobbling = true; } else { transform.localPosition = transform.localPosition * (1-f) + GetNextWobblyPosition() * f; } } }