using System.Threading; using Cysharp.Threading.Tasks; using Enums; using Services; using UnityEngine; using Utils; namespace Views { public class GemView : MonoBehaviour { private Gem gem; public Gem Gem => this.gem; private bool isFalling; [Header("Spawn Scale")] [SerializeField] private float spawnScaleFrom = 0f; [SerializeField] private float spawnScaleDuration = 0.12f; private CancellationTokenSource spawnScaleCts; public void Bind(Gem gem) { this.gem = gem; this.gameObject.SetActive(true); PlaySpawnScale(); } public void Unbind() { this.spawnScaleCts?.Cancel(); this.spawnScaleCts?.Dispose(); this.spawnScaleCts = null; this.gem = null; this.gameObject.SetActive(false); this.isFalling = false; } private void PlaySpawnScale() { this.spawnScaleCts?.Cancel(); this.spawnScaleCts?.Dispose(); this.spawnScaleCts = new CancellationTokenSource(); this.transform.localScale = Vector3.one * this.spawnScaleFrom; AnimateSpawnScaleAsync(this.spawnScaleCts.Token).Forget(); } private async UniTask AnimateSpawnScaleAsync(CancellationToken ct) { if (this.spawnScaleDuration <= 0f) { this.transform.localScale = Vector3.one; return; } float timer = 0f; while (timer < this.spawnScaleDuration) { ct.ThrowIfCancellationRequested(); timer += Time.deltaTime; float scale = Mathf.Clamp01(timer / this.spawnScaleDuration); scale = Mathf.SmoothStep(0f, 1f, scale); this.transform.localScale = Vector3.LerpUnclamped( Vector3.one * this.spawnScaleFrom, Vector3.one, scale ); await UniTask.Yield(PlayerLoopTiming.Update, ct); } this.transform.localScale = Vector3.one; } private async UniTask FallDelay() { float fallDelay = 1 * (this.gem.Position.y / 10f); await UniTask.WaitForSeconds(fallDelay); this.isFalling = true; } public async UniTaskVoid UpdatePosition(Vector2Int positionBasedOnIndex, float gemSpeed) { if (!this.isFalling) { await FallDelay(); } if (!this.isFalling) return; if (Vector2.Distance(this.transform.position, positionBasedOnIndex.ToVector2()) > 0.01f) { this.transform.position = Vector2.Lerp(this.transform.position, positionBasedOnIndex.ToVector2(), gemSpeed); } } } }