using UnityEngine; using UnityEngine.InputSystem; namespace BinxForge.CoinRoom { public sealed class CoinRoom : MonoBehaviour { public Rigidbody2D player; public Pickup[] coins; public Patrol patrol; public Camera worldCamera; public Vector2 spawn = new Vector2(-5, -3); public readonly RoundRules Rules = new RoundRules(); private Vector2 intent; public bool Active { get { return isActiveAndEnabled && Application.isFocused && Rules.Active; } } private void Start() { RestartRound(); } private void Update() { var keys = Keyboard.current; if (!Application.isFocused || keys == null) { intent = Vector2.zero; return; } if (keys.rKey.wasPressedThisFrame) RestartRound(); if (keys.pKey.wasPressedThisFrame) Rules.Pause(!Rules.Paused); intent = Active ? new Vector2( ((keys.dKey.isPressed || keys.rightArrowKey.isPressed) ? 1 : 0) - ((keys.aKey.isPressed || keys.leftArrowKey.isPressed) ? 1 : 0), ((keys.wKey.isPressed || keys.upArrowKey.isPressed) ? 1 : 0) - ((keys.sKey.isPressed || keys.downArrowKey.isPressed) ? 1 : 0) ) : Vector2.zero; } private void FixedUpdate() { if (player == null) return; if (Active) Rules.Tick(Time.fixedDeltaTime); RoundRules.Movement(intent.x, intent.y, out double x, out double y); player.linearVelocity = Active ? new Vector2((float)x, (float)y) : Vector2.zero; player.simulated = Active; } private void OnApplicationFocus(bool focused) { if (!focused) { Rules.Pause(true); intent = Vector2.zero; if (player != null) { player.linearVelocity = Vector2.zero; player.simulated = false; } } } private void OnDisable() { intent = Vector2.zero; if (player != null) { player.linearVelocity = Vector2.zero; player.simulated = false; } } public void RestartRound() { intent = Vector2.zero; Rules.Restart(); if (player != null) { player.simulated = false; player.position = spawn; player.linearVelocity = Vector2.zero; player.simulated = Application.isFocused; } if (coins != null) foreach (var coin in coins) if (coin != null) coin.gameObject.SetActive(true); if (patrol != null) patrol.ResetPose(); } private void OnGUI() { GUILayout.BeginArea(new Rect(16, 16, Mathf.Max(1, Mathf.Min(390, Screen.width - 32)), 170), GUI.skin.box); GUILayout.Label("Coin Room — " + Rules.Score + "/3 coins — " + Mathf.CeilToInt((float)Rules.Remaining) + " active seconds"); GUILayout.Label("Arrows / WASD: move. P: pause. R: restart."); GUILayout.Label("Collect all gold coins; avoid the red patrol."); GUILayout.Label(Rules.State != RoundState.Playing ? Rules.State.ToString() : Rules.Paused ? "Paused — press P to resume" : "Playing"); if (GUILayout.Button("Restart")) RestartRound(); GUILayout.EndArea(); } private void LateUpdate() { if (worldCamera != null && worldCamera.aspect > 0) worldCamera.orthographicSize = Mathf.Max(5, 7.75f / worldCamera.aspect); } } }