Time-based difficulty scaling with object pools and bird pooper restart improvements to the minigame

This commit is contained in:
Michal Pikulski
2025-12-16 23:21:10 +01:00
parent 0ff3fbbc70
commit 6133caec53
14 changed files with 994 additions and 280 deletions

View File

@@ -285,6 +285,7 @@ GameObject:
m_Component: m_Component:
- component: {fileID: 128829408} - component: {fileID: 128829408}
- component: {fileID: 128829407} - component: {fileID: 128829407}
- component: {fileID: 128829409}
m_Layer: 0 m_Layer: 0
m_Name: MinigameManager m_Name: MinigameManager
m_TagString: Untagged m_TagString: Untagged
@@ -307,6 +308,7 @@ MonoBehaviour:
player: {fileID: 941621859} player: {fileID: 941621859}
obstacleSpawner: {fileID: 938885957} obstacleSpawner: {fileID: 938885957}
targetSpawner: {fileID: 1838778561} targetSpawner: {fileID: 1838778561}
tapToStartController: {fileID: 128829409}
gameOverScreen: {fileID: 81231374} gameOverScreen: {fileID: 81231374}
poopPrefab: {fileID: 5552423787977869117, guid: 066f9990a9b1f5547b387633d5d204c0, type: 3} poopPrefab: {fileID: 5552423787977869117, guid: 066f9990a9b1f5547b387633d5d204c0, type: 3}
poopCooldown: 0.5 poopCooldown: 0.5
@@ -325,6 +327,23 @@ Transform:
m_Children: [] m_Children: []
m_Father: {fileID: 0} m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &128829409
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 128829406}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 2a6ee5aca3ca423c82b57e16c0b2cca3, type: 3}
m_Name:
m_EditorClassIdentifier: AppleHillsScripts::Minigames.BirdPooper.TapToStartController
fingerContainer: {fileID: 2064126204}
fingerImage: {fileID: 1481863789}
blinkDuration: 1.5
minAlpha: 0.3
maxAlpha: 1
--- !u!1 &402349268 --- !u!1 &402349268
GameObject: GameObject:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
@@ -771,53 +790,6 @@ MonoBehaviour:
despawnPoint: {fileID: 938473626} despawnPoint: {fileID: 938473626}
referenceMarker: {fileID: 1143700529} referenceMarker: {fileID: 1143700529}
cameraAdapter: {fileID: 2103114179} cameraAdapter: {fileID: 2103114179}
obstaclePrefabs:
- {fileID: 8855270423038321603, guid: 20ae02a8f50484045aaf3dcee33fb9a2, type: 3}
- {fileID: 2514399078413048981, guid: ee834e7efcf7d8749881f71f8b0da99c, type: 3}
- {fileID: 842802843766402460, guid: cdc806fd167bba3488797031a28657fa, type: 3}
- {fileID: 4239333156730914246, guid: 332d8cce2ed99054c83ecf84fbfa14c8, type: 3}
- {fileID: 6660502783540694524, guid: 5d42fc70e5838544ab654e30aa4b0c48, type: 3}
- {fileID: 2421410811796775077, guid: 371a09b68a5c0654bac9ba58ad3bcbe5, type: 3}
- {fileID: 1408173265900928789, guid: 871373a85e5da0e4cafdf0e47496e105, type: 3}
- {fileID: 1408173265900928789, guid: d2998934362713545a040d7017a1bd36, type: 3}
- {fileID: 1408173265900928789, guid: 146d99398c0e7964dbed504e256adab7, type: 3}
- {fileID: 1408173265900928789, guid: dc8a19e9a4d30b44596237d915b3b73f, type: 3}
- {fileID: 1408173265900928789, guid: 471f367e14f9cfb4fb2c40d799d4c292, type: 3}
- {fileID: 1408173265900928789, guid: 5f1734c5705cdfd49ae3180d678d28b3, type: 3}
- {fileID: 1408173265900928789, guid: 6bc84c3ea9854b54f85a8fb69c769790, type: 3}
- {fileID: 1408173265900928789, guid: 166c7e1bfcc4c854fab0af51cdfff746, type: 3}
- {fileID: 1408173265900928789, guid: 65810bfd58ebbaf4482527452258ae50, type: 3}
- {fileID: 1408173265900928789, guid: ae3986a7db087c845b618a9c897705ec, type: 3}
minSpawnInterval: 2
maxSpawnInterval: 8
difficultyRampDuration: 360
difficultyCurve:
serializedVersion: 2
m_Curve:
- serializedVersion: 3
time: 0
value: 0
inSlope: 0
outSlope: 0
tangentMode: 0
weightedMode: 0
inWeight: 0
outWeight: 0
- serializedVersion: 3
time: 1
value: 1
inSlope: 2
outSlope: 2
tangentMode: 0
weightedMode: 0
inWeight: 0
outWeight: 0
m_PreInfinity: 2
m_PostInfinity: 2
m_RotationOrder: 4
intervalJitter: 0.3
recentDecayDuration: 60
minRecentWeight: 0.05
--- !u!1 &941621855 --- !u!1 &941621855
GameObject: GameObject:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
@@ -1484,6 +1456,81 @@ Transform:
m_Children: [] m_Children: []
m_Father: {fileID: 0} m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1481863787
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1481863788}
- component: {fileID: 1481863790}
- component: {fileID: 1481863789}
m_Layer: 5
m_Name: Image
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &1481863788
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1481863787}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1.18, y: 1.18, z: 1.18}
m_ConstrainProportionsScale: 1
m_Children: []
m_Father: {fileID: 2064126205}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0.5, y: 0.5}
m_AnchorMax: {x: 0.5, y: 0.5}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 316, y: 246}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!114 &1481863789
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1481863787}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3}
m_Name:
m_EditorClassIdentifier: UnityEngine.UI::UnityEngine.UI.Image
m_Material: {fileID: 0}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_RaycastPadding: {x: 0, y: 0, z: 0, w: 0}
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_Sprite: {fileID: -7164639588303836088, guid: 6fee60c82a4f504419e535456268a19e, type: 3}
m_Type: 0
m_PreserveAspect: 0
m_FillCenter: 1
m_FillMethod: 4
m_FillAmount: 1
m_FillClockwise: 1
m_FillOrigin: 0
m_UseSpriteMesh: 0
m_PixelsPerUnitMultiplier: 1
--- !u!222 &1481863790
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1481863787}
m_CullTransparentMesh: 1
--- !u!1 &1498486830 --- !u!1 &1498486830
GameObject: GameObject:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0
@@ -1615,6 +1662,7 @@ RectTransform:
m_Children: m_Children:
- {fileID: 1088771378} - {fileID: 1088771378}
- {fileID: 81231372} - {fileID: 81231372}
- {fileID: 2064126205}
m_Father: {fileID: 0} m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0} m_AnchorMin: {x: 0, y: 0}
@@ -1844,6 +1892,42 @@ MonoBehaviour:
- {fileID: 8373178063207716143, guid: 020f7494c613b06479ccad2c4cedde0f, type: 3} - {fileID: 8373178063207716143, guid: 020f7494c613b06479ccad2c4cedde0f, type: 3}
minTargetSpawnInterval: 9 minTargetSpawnInterval: 9
maxTargetSpawnInterval: 15 maxTargetSpawnInterval: 15
--- !u!1 &2064126204
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 2064126205}
m_Layer: 5
m_Name: StartGamePrompt
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &2064126205
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2064126204}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 1481863788}
m_Father: {fileID: 1536057440}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 1, y: 1}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!1 &2103114174 --- !u!1 &2103114174
GameObject: GameObject:
m_ObjectHideFlags: 0 m_ObjectHideFlags: 0

View File

@@ -1,4 +1,5 @@
using AppleHills.Core.Settings; using AppleHills.Core.Settings;
using Minigames.BirdPooper;
using UnityEngine; using UnityEngine;
namespace Core.Settings namespace Core.Settings
@@ -33,8 +34,8 @@ namespace Core.Settings
[Tooltip("Obstacle scroll speed in units/s")] [Tooltip("Obstacle scroll speed in units/s")]
[SerializeField] private float obstacleMoveSpeed = 5f; [SerializeField] private float obstacleMoveSpeed = 5f;
[Tooltip("Time between obstacle spawns in seconds")] [Tooltip("Obstacle spawning configuration (pools, timing, difficulty)")]
[SerializeField] private float obstacleSpawnInterval = 2f; [SerializeField] private ObstacleSpawnConfig obstacleSpawnConfiguration;
[Tooltip("X position where obstacles spawn (off-screen right)")] [Tooltip("X position where obstacles spawn (off-screen right)")]
[SerializeField] private float obstacleSpawnXPosition = 12f; [SerializeField] private float obstacleSpawnXPosition = 12f;
@@ -71,7 +72,7 @@ namespace Core.Settings
public float MaxRotationAngle => maxRotationAngle; public float MaxRotationAngle => maxRotationAngle;
public float RotationSpeed => rotationSpeed; public float RotationSpeed => rotationSpeed;
public float ObstacleMoveSpeed => obstacleMoveSpeed; public float ObstacleMoveSpeed => obstacleMoveSpeed;
public float ObstacleSpawnInterval => obstacleSpawnInterval; public ObstacleSpawnConfig ObstacleSpawnConfiguration => obstacleSpawnConfiguration;
public float ObstacleSpawnXPosition => obstacleSpawnXPosition; public float ObstacleSpawnXPosition => obstacleSpawnXPosition;
public float ObstacleDestroyXPosition => obstacleDestroyXPosition; public float ObstacleDestroyXPosition => obstacleDestroyXPosition;
public float ObstacleMinSpawnY => obstacleMinSpawnY; public float ObstacleMinSpawnY => obstacleMinSpawnY;
@@ -91,9 +92,14 @@ namespace Core.Settings
maxFallSpeed = Mathf.Max(0f, maxFallSpeed); maxFallSpeed = Mathf.Max(0f, maxFallSpeed);
maxRotationAngle = Mathf.Clamp(maxRotationAngle, 0f, 90f); maxRotationAngle = Mathf.Clamp(maxRotationAngle, 0f, 90f);
rotationSpeed = Mathf.Max(0.1f, rotationSpeed); rotationSpeed = Mathf.Max(0.1f, rotationSpeed);
obstacleSpawnInterval = Mathf.Max(0.1f, obstacleSpawnInterval);
targetMoveSpeed = Mathf.Max(0.1f, targetMoveSpeed); targetMoveSpeed = Mathf.Max(0.1f, targetMoveSpeed);
targetSpawnInterval = Mathf.Max(0.1f, targetSpawnInterval); targetSpawnInterval = Mathf.Max(0.1f, targetSpawnInterval);
// Validate obstacle spawn configuration
if (obstacleSpawnConfiguration != null)
{
obstacleSpawnConfiguration.Validate();
}
} }
} }
} }

View File

@@ -1,8 +1,10 @@
namespace Core.Settings using Minigames.BirdPooper;
namespace Core.Settings
{ {
/// <summary> /// <summary>
/// Settings interface for Bird Pooper minigame. /// Settings interface for Bird Pooper minigame.
/// Accessed via GameManager.GetSettingsObject<IBirdPooperSettings>() /// Accessed via GameManager.GetSettingsObject of IBirdPooperSettings
/// </summary> /// </summary>
public interface IBirdPooperSettings public interface IBirdPooperSettings
{ {
@@ -19,12 +21,14 @@
// Obstacles // Obstacles
float ObstacleMoveSpeed { get; } float ObstacleMoveSpeed { get; }
float ObstacleSpawnInterval { get; }
float ObstacleSpawnXPosition { get; } float ObstacleSpawnXPosition { get; }
float ObstacleDestroyXPosition { get; } float ObstacleDestroyXPosition { get; }
float ObstacleMinSpawnY { get; } float ObstacleMinSpawnY { get; }
float ObstacleMaxSpawnY { get; } float ObstacleMaxSpawnY { get; }
// Obstacle Spawning Configuration
ObstacleSpawnConfig ObstacleSpawnConfiguration { get; }
// Poop Projectile // Poop Projectile
float PoopFallSpeed { get; } float PoopFallSpeed { get; }
float PoopDestroyYPosition { get; } float PoopDestroyYPosition { get; }

View File

@@ -15,11 +15,12 @@ namespace Minigames.BirdPooper
public UnityEngine.Events.UnityEvent OnFlap; public UnityEngine.Events.UnityEvent OnFlap;
public UnityEngine.Events.UnityEvent OnPlayerDamaged; public UnityEngine.Events.UnityEvent OnPlayerDamaged;
private Rigidbody2D rb; private Rigidbody2D _rb;
private IBirdPooperSettings settings; private IBirdPooperSettings _settings;
private float verticalVelocity = 0f; private float _verticalVelocity;
private bool isDead = false; private bool _isDead;
private float fixedXPosition; // Store the initial X position from the scene private float _fixedXPosition; // Store the initial X position from the scene
private bool _isInitialized; // Flag to control when physics/input are active
internal override void OnManagedAwake() internal override void OnManagedAwake()
{ {
@@ -31,33 +32,49 @@ namespace Minigames.BirdPooper
if (OnPlayerDamaged == null) if (OnPlayerDamaged == null)
OnPlayerDamaged = new UnityEngine.Events.UnityEvent(); OnPlayerDamaged = new UnityEngine.Events.UnityEvent();
// Load settings // Only cache component references - NO setup yet
settings = GameManager.GetSettingsObject<IBirdPooperSettings>(); _rb = GetComponent<Rigidbody2D>();
if (settings == null) if (_rb == null)
{
Debug.LogError("[BirdPlayerController] BirdPooperSettings not found!");
return;
}
// Get Rigidbody2D component (Dynamic with gravityScale = 0)
rb = GetComponent<Rigidbody2D>();
if (rb != null)
{
rb.gravityScale = 0f; // Disable Unity physics gravity
rb.bodyType = RigidbodyType2D.Kinematic; // Kinematic = manual movement, no physics forces
// Store the initial X position from the scene
fixedXPosition = rb.position.x;
Debug.Log($"[BirdPlayerController] Fixed X position set to: {fixedXPosition}");
}
else
{ {
Debug.LogError("[BirdPlayerController] Rigidbody2D component not found!"); Debug.LogError("[BirdPlayerController] Rigidbody2D component not found!");
return;
} }
// Register as default consumer (gets input if nothing else consumes it) // Load settings
// This allows UI buttons to work while still flapping when tapping empty space _settings = GameManager.GetSettingsObject<IBirdPooperSettings>();
if (_settings == null)
{
Debug.LogError("[BirdPlayerController] BirdPooperSettings not found!");
}
Debug.Log("[BirdPlayerController] References cached, waiting for initialization...");
}
/// <summary>
/// Initializes the player controller - enables physics and input.
/// Should be called by BirdPooperGameManager when ready to start the game.
/// </summary>
public void Initialize()
{
if (_isInitialized)
{
Debug.LogWarning("[BirdPlayerController] Already initialized!");
return;
}
if (_rb == null || _settings == null)
{
Debug.LogError("[BirdPlayerController] Cannot initialize - missing references!");
return;
}
// Setup physics
_rb.gravityScale = 0f; // Disable Unity physics gravity
_rb.bodyType = RigidbodyType2D.Kinematic; // Kinematic = manual movement, no physics forces
// Store the initial X position from the scene
_fixedXPosition = _rb.position.x;
// Register as default input consumer
if (Input.InputManager.Instance != null) if (Input.InputManager.Instance != null)
{ {
Input.InputManager.Instance.SetDefaultConsumer(this); Input.InputManager.Instance.SetDefaultConsumer(this);
@@ -67,52 +84,74 @@ namespace Minigames.BirdPooper
{ {
Debug.LogError("[BirdPlayerController] InputManager instance not found!"); Debug.LogError("[BirdPlayerController] InputManager instance not found!");
} }
_isInitialized = true;
Debug.Log($"[BirdPlayerController] Initialized! Fixed X position: {_fixedXPosition}");
} }
private void Update() private void Update()
{ {
if (!isDead && settings != null && rb != null) // Only run physics/movement if initialized
{ if (!_isInitialized || _isDead || _settings == null || _rb == null)
// Apply manual gravity return;
verticalVelocity -= settings.Gravity * Time.deltaTime;
// Apply manual gravity
// Cap fall speed (terminal velocity) _verticalVelocity -= _settings.Gravity * Time.deltaTime;
if (verticalVelocity < -settings.MaxFallSpeed)
verticalVelocity = -settings.MaxFallSpeed; // Cap fall speed (terminal velocity)
if (_verticalVelocity < -_settings.MaxFallSpeed)
// Update position manually _verticalVelocity = -_settings.MaxFallSpeed;
Vector2 newPosition = rb.position;
newPosition.y += verticalVelocity * Time.deltaTime; // Update position manually
newPosition.x = fixedXPosition; // Keep X fixed at scene-configured position Vector2 newPosition = _rb.position;
newPosition.y += _verticalVelocity * Time.deltaTime;
// Clamp Y position to bounds newPosition.x = _fixedXPosition; // Keep X fixed at scene-configured position
newPosition.y = Mathf.Clamp(newPosition.y, settings.MinY, settings.MaxY);
// Clamp Y position to bounds
rb.MovePosition(newPosition); newPosition.y = Mathf.Clamp(newPosition.y, _settings.MinY, _settings.MaxY);
// Update rotation based on velocity _rb.MovePosition(newPosition);
UpdateRotation();
} // Update rotation based on velocity
UpdateRotation();
} }
#region ITouchInputConsumer Implementation #region ITouchInputConsumer Implementation
public void OnTap(Vector2 tapPosition) public void OnTap(Vector2 tapPosition)
{ {
if (!isDead && settings != null) // Only respond to input if initialized and alive
{ if (!_isInitialized || _isDead || _settings == null)
verticalVelocity = settings.FlapForce; return;
Debug.Log($"[BirdPlayerController] Flap! velocity = {verticalVelocity}");
Flap();
// Emit flap event
OnFlap?.Invoke();
}
} }
public void OnHoldStart(Vector2 position) { } public void OnHoldStart(Vector2 position) { }
public void OnHoldMove(Vector2 position) { } public void OnHoldMove(Vector2 position) { }
public void OnHoldEnd(Vector2 position) { } public void OnHoldEnd(Vector2 position) { }
#endregion
#region Player Actions
/// <summary>
/// Makes the bird flap, applying upward velocity.
/// Can be called by input system or externally (e.g., for first tap).
/// </summary>
public void Flap()
{
if (!_isInitialized || _isDead || _settings == null)
return;
_verticalVelocity = _settings.FlapForce;
Debug.Log($"[BirdPlayerController] Flap! velocity = {_verticalVelocity}");
// Emit flap event
OnFlap?.Invoke();
}
#endregion #endregion
#region Rotation #region Rotation
@@ -123,19 +162,19 @@ namespace Minigames.BirdPooper
/// </summary> /// </summary>
private void UpdateRotation() private void UpdateRotation()
{ {
if (settings == null) return; if (_settings == null) return;
// Map velocity to rotation angle // Map velocity to rotation angle
// When falling at max speed (-MaxFallSpeed): -MaxRotationAngle (down) // When falling at max speed (-MaxFallSpeed): -MaxRotationAngle (down)
// When at flap velocity (+FlapForce): +MaxRotationAngle (up) // When at flap velocity (+FlapForce): +MaxRotationAngle (up)
float velocityPercent = Mathf.InverseLerp( float velocityPercent = Mathf.InverseLerp(
-settings.MaxFallSpeed, -_settings.MaxFallSpeed,
settings.FlapForce, _settings.FlapForce,
verticalVelocity _verticalVelocity
); );
float targetAngle = Mathf.Lerp( float targetAngle = Mathf.Lerp(
-settings.MaxRotationAngle, -_settings.MaxRotationAngle,
settings.MaxRotationAngle, _settings.MaxRotationAngle,
velocityPercent velocityPercent
); );
@@ -148,7 +187,7 @@ namespace Minigames.BirdPooper
float smoothedAngle = Mathf.Lerp( float smoothedAngle = Mathf.Lerp(
currentAngle, currentAngle,
targetAngle, targetAngle,
settings.RotationSpeed * Time.deltaTime _settings.RotationSpeed * Time.deltaTime
); );
// Apply rotation to Z axis only (2D rotation) // Apply rotation to Z axis only (2D rotation)
@@ -175,10 +214,10 @@ namespace Minigames.BirdPooper
private void HandleDeath() private void HandleDeath()
{ {
// Only process death once // Only process death once
if (isDead) return; if (_isDead) return;
isDead = true; _isDead = true;
verticalVelocity = 0f; _verticalVelocity = 0f;
Debug.Log("[BirdPlayerController] Bird died!"); Debug.Log("[BirdPlayerController] Bird died!");
// Emit damage event - let the game manager handle UI // Emit damage event - let the game manager handle UI
@@ -187,9 +226,9 @@ namespace Minigames.BirdPooper
#endregion #endregion
#region Public Properties #region Public Accessors
public bool IsDead => isDead; public bool IsDead => _isDead;
#endregion #endregion
} }

View File

@@ -17,12 +17,13 @@ namespace Minigames.BirdPooper
[SerializeField] private BirdPlayerController player; [SerializeField] private BirdPlayerController player;
[SerializeField] private ObstacleSpawner obstacleSpawner; [SerializeField] private ObstacleSpawner obstacleSpawner;
[SerializeField] private TargetSpawner targetSpawner; [SerializeField] private TargetSpawner targetSpawner;
[SerializeField] private TapToStartController tapToStartController;
[SerializeField] private GameOverScreen gameOverScreen; [SerializeField] private GameOverScreen gameOverScreen;
[SerializeField] private GameObject poopPrefab; [SerializeField] private GameObject poopPrefab;
[Header("Game State")] [Header("Game State")]
private int targetsHit; private int _targetsHit;
private bool isGameOver; private bool _isGameOver;
[Header("Input")] [Header("Input")]
[Tooltip("Minimum seconds between consecutive poop spawns")] [Tooltip("Minimum seconds between consecutive poop spawns")]
@@ -60,6 +61,11 @@ namespace Minigames.BirdPooper
Debug.LogWarning("[BirdPooperGameManager] TargetSpawner reference not assigned! Targets will not spawn."); Debug.LogWarning("[BirdPooperGameManager] TargetSpawner reference not assigned! Targets will not spawn.");
} }
if (tapToStartController == null)
{
Debug.LogError("[BirdPooperGameManager] TapToStartController reference not assigned!");
}
if (gameOverScreen == null) if (gameOverScreen == null)
{ {
Debug.LogError("[BirdPooperGameManager] GameOverScreen reference not assigned!"); Debug.LogError("[BirdPooperGameManager] GameOverScreen reference not assigned!");
@@ -76,34 +82,76 @@ namespace Minigames.BirdPooper
} }
} }
internal override void OnManagedStart() /// <summary>
/// Called after scene is fully loaded and any save data is restored.
/// Activates tap-to-start UI instead of starting immediately.
/// </summary>
internal override void OnSceneRestoreCompleted()
{ {
base.OnManagedStart(); base.OnSceneRestoreCompleted();
Debug.Log("[BirdPooperGameManager] Scene fully loaded, activating tap-to-start...");
if (tapToStartController != null)
{
tapToStartController.Activate();
}
else
{
Debug.LogError("[BirdPooperGameManager] TapToStartController missing! Starting game immediately as fallback.");
BeginMinigame();
}
}
/// <summary>
/// Central method to begin the minigame.
/// Initializes player, starts spawners, and sets up game state.
/// </summary>
public void BeginMinigame()
{
// Initialize game state // Initialize game state
isGameOver = false; _isGameOver = false;
targetsHit = 0; _targetsHit = 0;
// Subscribe to player events // Initialize and enable player
if (player != null) if (player != null)
{ {
player.Initialize();
player.OnPlayerDamaged.AddListener(HandlePlayerDamaged); player.OnPlayerDamaged.AddListener(HandlePlayerDamaged);
Debug.Log("[BirdPooperGameManager] Subscribed to player damaged event");
// Make bird do initial flap so first tap feels responsive
player.Flap();
Debug.Log("[BirdPooperGameManager] Player initialized and event subscribed");
}
else
{
Debug.LogError("[BirdPooperGameManager] Cannot begin minigame - player reference missing!");
} }
// Start obstacle spawning // Start obstacle spawning
if (obstacleSpawner != null) if (obstacleSpawner != null)
{ {
obstacleSpawner.StartSpawning(); obstacleSpawner.StartSpawning();
Debug.Log("[BirdPooperGameManager] Started obstacle spawning"); Debug.Log("[BirdPooperGameManager] Obstacle spawner started");
}
else
{
Debug.LogError("[BirdPooperGameManager] Cannot begin minigame - obstacle spawner reference missing!");
} }
// Start target spawning // Start target spawning
if (targetSpawner != null) if (targetSpawner != null)
{ {
targetSpawner.StartSpawning(); targetSpawner.StartSpawning();
Debug.Log("[BirdPooperGameManager] Started target spawning"); Debug.Log("[BirdPooperGameManager] Target spawner started");
} }
else
{
Debug.LogWarning("[BirdPooperGameManager] Target spawner reference missing - targets will not spawn");
}
Debug.Log("[BirdPooperGameManager] ✅ Minigame started successfully!");
} }
internal override void OnManagedDestroy() internal override void OnManagedDestroy()
@@ -129,10 +177,10 @@ namespace Minigames.BirdPooper
/// </summary> /// </summary>
private void HandlePlayerDamaged() private void HandlePlayerDamaged()
{ {
if (isGameOver) return; if (_isGameOver) return;
isGameOver = true; _isGameOver = true;
Debug.Log($"[BirdPooperGameManager] Player damaged - Game Over! Targets Hit: {targetsHit}"); Debug.Log($"[BirdPooperGameManager] Player damaged - Game Over! Targets Hit: {_targetsHit}");
// Stop spawning obstacles // Stop spawning obstacles
if (obstacleSpawner != null) if (obstacleSpawner != null)
@@ -167,7 +215,7 @@ namespace Minigames.BirdPooper
if (Time.time < _lastPoopTime + poopCooldown) if (Time.time < _lastPoopTime + poopCooldown)
return; return;
if (isGameOver || player == null || poopPrefab == null) if (_isGameOver || player == null || poopPrefab == null)
return; return;
Vector3 spawnPosition = player.transform.position; Vector3 spawnPosition = player.transform.position;
@@ -183,16 +231,17 @@ namespace Minigames.BirdPooper
/// </summary> /// </summary>
public void OnTargetHit() public void OnTargetHit()
{ {
if (isGameOver) return; if (_isGameOver) return;
targetsHit++; _targetsHit++;
Debug.Log($"[BirdPooperGameManager] Target Hit! Total: {targetsHit}"); Debug.Log($"[BirdPooperGameManager] Target Hit! Total: {_targetsHit}");
} }
#region Public Accessors #region Public Accessors
public bool IsGameOver => isGameOver; public bool IsGameOver => _isGameOver;
public int TargetsHit => targetsHit; public int TargetsHit => _targetsHit;
public BirdPlayerController Player => player;
#endregion #endregion
} }

View File

@@ -0,0 +1,111 @@
using System;
using UnityEngine;
namespace Minigames.BirdPooper
{
/// <summary>
/// Container for a pool of obstacle prefabs at a specific difficulty tier.
/// Pools are ordered by difficulty, with pool[0] being the easiest.
/// </summary>
[Serializable]
public class ObstaclePool
{
[Tooltip("Obstacles in this difficulty tier")]
public GameObject[] obstacles;
}
/// <summary>
/// Configuration for obstacle spawning in Bird Pooper minigame.
/// Includes difficulty pools, spawn timing, and diversity settings.
/// </summary>
[Serializable]
public class ObstacleSpawnConfig
{
[Header("Difficulty Pools")]
[Tooltip("Obstacle pools ordered by difficulty (pool[0] = easiest, always active)")]
public ObstaclePool[] obstaclePools;
[Tooltip("Times (in seconds) when each additional pool unlocks. Length should be obstaclePools.Length - 1. At poolUnlockTimes[i], pool[i+1] becomes available.")]
public float[] poolUnlockTimes;
[Header("Spawn Timing")]
[Tooltip("Minimum interval between spawns (seconds) - represents high difficulty")]
public float minSpawnInterval = 1f;
[Tooltip("Maximum interval between spawns (seconds) - represents low difficulty")]
public float maxSpawnInterval = 2f;
[Header("Difficulty Scaling")]
[Tooltip("Time in seconds for difficulty to ramp from 0 to 1")]
public float difficultyRampDuration = 60f;
[Tooltip("Curve mapping normalized time (0..1) to difficulty (0..1). Default is linear.")]
public AnimationCurve difficultyCurve = AnimationCurve.Linear(0f, 0f, 1f, 1f);
[Tooltip("Maximum jitter applied to computed interval (fractional). 0.1 = +/-10% jitter")]
public float intervalJitter = 0.05f;
[Header("Recency / Diversity")]
[Tooltip("Time in seconds it takes for a recently-used prefab to recover back to full weight")]
public float recentDecayDuration = 10f;
[Tooltip("Minimum weight (0..1) applied to a just-used prefab so it can still appear occasionally")]
[Range(0f, 1f)]
public float minRecentWeight = 0.05f;
/// <summary>
/// Validates the configuration and logs warnings for invalid settings.
/// </summary>
public void Validate()
{
// Validate pools
if (obstaclePools == null || obstaclePools.Length == 0)
{
Debug.LogError("[ObstacleSpawnConfig] No obstacle pools defined!");
return;
}
// Validate pool unlock times
int expectedUnlockTimes = obstaclePools.Length - 1;
if (poolUnlockTimes == null)
{
Debug.LogWarning($"[ObstacleSpawnConfig] poolUnlockTimes is null. Expected {expectedUnlockTimes} entries. Only pool[0] will be available.");
}
else if (poolUnlockTimes.Length != expectedUnlockTimes)
{
Debug.LogWarning($"[ObstacleSpawnConfig] poolUnlockTimes.Length ({poolUnlockTimes.Length}) does not match expected value ({expectedUnlockTimes}). Should be obstaclePools.Length - 1.");
}
// Validate spawn intervals
if (minSpawnInterval < 0f)
{
Debug.LogWarning("[ObstacleSpawnConfig] minSpawnInterval is negative. Clamping to 0.");
}
if (maxSpawnInterval < 0f)
{
Debug.LogWarning("[ObstacleSpawnConfig] maxSpawnInterval is negative. Clamping to 0.");
}
if (minSpawnInterval > maxSpawnInterval)
{
Debug.LogWarning("[ObstacleSpawnConfig] minSpawnInterval is greater than maxSpawnInterval. Values should be swapped.");
}
// Validate difficulty ramp
if (difficultyRampDuration < 0.01f)
{
Debug.LogWarning("[ObstacleSpawnConfig] difficultyRampDuration is too small. Should be at least 0.01.");
}
// Validate recency settings
if (recentDecayDuration < 0.01f)
{
Debug.LogWarning("[ObstacleSpawnConfig] recentDecayDuration is too small. Should be at least 0.01.");
}
if (minRecentWeight < 0f || minRecentWeight > 1f)
{
Debug.LogWarning("[ObstacleSpawnConfig] minRecentWeight should be between 0 and 1.");
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 74f4387c76774225afa2d02d590d5ad4
timeCreated: 1765918010

View File

@@ -4,6 +4,7 @@ using Core.Settings;
using Core.Lifecycle; using Core.Lifecycle;
using AppleHillsCamera; using AppleHillsCamera;
using System.Text; using System.Text;
using System.Collections.Generic;
namespace Minigames.BirdPooper namespace Minigames.BirdPooper
{ {
@@ -11,6 +12,7 @@ namespace Minigames.BirdPooper
/// Spawns obstacles at regular intervals for Bird Pooper minigame. /// Spawns obstacles at regular intervals for Bird Pooper minigame.
/// Uses Transform references for spawn and despawn positions instead of hardcoded values. /// Uses Transform references for spawn and despawn positions instead of hardcoded values.
/// All obstacles are spawned at Y = 0 (prefabs should be authored accordingly). /// All obstacles are spawned at Y = 0 (prefabs should be authored accordingly).
/// Supports dynamic difficulty pools that unlock over time.
/// </summary> /// </summary>
public class ObstacleSpawner : ManagedBehaviour public class ObstacleSpawner : ManagedBehaviour
{ {
@@ -20,6 +22,9 @@ namespace Minigames.BirdPooper
[Tooltip("Transform marking where obstacles despawn (off-screen left)")] [Tooltip("Transform marking where obstacles despawn (off-screen left)")]
[SerializeField] private Transform despawnPoint; [SerializeField] private Transform despawnPoint;
[Tooltip("Optional parent transform for spawned obstacles (for scene organization)")]
[SerializeField] private Transform obstacleContainer;
[Header("EdgeAnchor References")] [Header("EdgeAnchor References")]
[Tooltip("ScreenReferenceMarker to pass to spawned obstacles")] [Tooltip("ScreenReferenceMarker to pass to spawned obstacles")]
@@ -28,55 +33,45 @@ namespace Minigames.BirdPooper
[Tooltip("CameraScreenAdapter to pass to spawned obstacles")] [Tooltip("CameraScreenAdapter to pass to spawned obstacles")]
[SerializeField] private CameraScreenAdapter cameraAdapter; [SerializeField] private CameraScreenAdapter cameraAdapter;
[Header("Obstacle Prefabs")] private IBirdPooperSettings _settings;
[Tooltip("Array of obstacle prefabs to spawn randomly")] private ObstacleSpawnConfig _spawnConfig;
[SerializeField] private GameObject[] obstaclePrefabs; private float _spawnTimer;
private bool _isSpawning;
[Header("Spawn Timing")]
[Tooltip("Minimum interval between spawns (seconds)")]
[SerializeField] private float minSpawnInterval = 1f;
[Tooltip("Maximum interval between spawns (seconds)")]
[SerializeField] private float maxSpawnInterval = 2f;
[Header("Difficulty")]
[Tooltip("Time in seconds for difficulty to ramp from 0 to 1")]
[SerializeField] private float difficultyRampDuration = 60f;
[Tooltip("Curve mapping normalized time (0..1) to difficulty (0..1). Default is linear.")]
[SerializeField] private AnimationCurve difficultyCurve = AnimationCurve.Linear(0f, 0f, 1f, 1f);
[Tooltip("Maximum jitter applied to computed interval (fractional). 0.1 = +/-10% jitter")]
[SerializeField] private float intervalJitter = 0.05f;
[Header("Recency / Diversity")]
[Tooltip("Time in seconds it takes for a recently-used prefab to recover back to full weight")]
[SerializeField] private float recentDecayDuration = 10f;
[Tooltip("Minimum weight (0..1) applied to a just-used prefab so it can still appear occasionally")]
[Range(0f, 1f)]
[SerializeField] private float minRecentWeight = 0.05f;
private IBirdPooperSettings settings;
private float spawnTimer;
private bool isSpawning;
private float _currentSpawnInterval = 1f; private float _currentSpawnInterval = 1f;
// difficulty tracking // Difficulty tracking
private float _elapsedTime = 0f; private float _elapsedTime;
// recency tracking // Master obstacle list for recency tracking
private List<GameObject> _allObstacles;
private Dictionary<GameObject, int> _obstacleToGlobalIndex;
private float[] _lastUsedTimes; private float[] _lastUsedTimes;
internal override void OnManagedAwake() /// <summary>
/// Initializes the obstacle spawner by loading settings, validating references, and building obstacle pools.
/// Should be called once before spawning begins.
/// </summary>
private void Initialize()
{ {
base.OnManagedAwake();
// Load settings // Load settings
settings = GameManager.GetSettingsObject<IBirdPooperSettings>(); _settings = GameManager.GetSettingsObject<IBirdPooperSettings>();
if (settings == null) if (_settings == null)
{ {
Debug.LogError("[ObstacleSpawner] BirdPooperSettings not found!"); Debug.LogError("[ObstacleSpawner] BirdPooperSettings not found! Cannot initialize.");
// continue — we now use min/max interval fields instead of relying on settings return;
} }
// Validate references _spawnConfig = _settings.ObstacleSpawnConfiguration;
if (_spawnConfig == null)
{
Debug.LogError("[ObstacleSpawner] ObstacleSpawnConfiguration not found in settings! Cannot initialize.");
return;
}
// Validate spawn configuration
_spawnConfig.Validate();
// Validate scene references
if (spawnPoint == null) if (spawnPoint == null)
{ {
Debug.LogError("[ObstacleSpawner] Spawn Point not assigned! Please assign a Transform in the Inspector."); Debug.LogError("[ObstacleSpawner] Spawn Point not assigned! Please assign a Transform in the Inspector.");
@@ -87,11 +82,6 @@ namespace Minigames.BirdPooper
Debug.LogError("[ObstacleSpawner] Despawn Point not assigned! Please assign a Transform in the Inspector."); Debug.LogError("[ObstacleSpawner] Despawn Point not assigned! Please assign a Transform in the Inspector.");
} }
if (obstaclePrefabs == null || obstaclePrefabs.Length == 0)
{
Debug.LogError("[ObstacleSpawner] No obstacle prefabs assigned! Please assign at least one prefab in the Inspector.");
}
if (referenceMarker == null) if (referenceMarker == null)
{ {
Debug.LogError("[ObstacleSpawner] ScreenReferenceMarker not assigned! Obstacles need this for EdgeAnchor positioning."); Debug.LogError("[ObstacleSpawner] ScreenReferenceMarker not assigned! Obstacles need this for EdgeAnchor positioning.");
@@ -102,58 +92,100 @@ namespace Minigames.BirdPooper
Debug.LogWarning("[ObstacleSpawner] CameraScreenAdapter not assigned. EdgeAnchor will attempt to auto-find camera."); Debug.LogWarning("[ObstacleSpawner] CameraScreenAdapter not assigned. EdgeAnchor will attempt to auto-find camera.");
} }
// Validate interval range // Build master obstacle list from all pools
if (minSpawnInterval < 0f) minSpawnInterval = 0f; BuildMasterObstacleList();
if (maxSpawnInterval < 0f) maxSpawnInterval = 0f;
if (minSpawnInterval > maxSpawnInterval) Debug.Log("[ObstacleSpawner] Initialized successfully with pool-based difficulty scaling");
}
/// <summary>
/// Builds a master list of all obstacles across all pools and creates index mappings for recency tracking.
/// </summary>
private void BuildMasterObstacleList()
{
_allObstacles = new List<GameObject>();
_obstacleToGlobalIndex = new Dictionary<GameObject, int>();
if (_spawnConfig.obstaclePools == null || _spawnConfig.obstaclePools.Length == 0)
{ {
float tmp = minSpawnInterval; Debug.LogError("[ObstacleSpawner] No obstacle pools defined in configuration!");
minSpawnInterval = maxSpawnInterval; return;
maxSpawnInterval = tmp;
Debug.LogWarning("[ObstacleSpawner] minSpawnInterval was greater than maxSpawnInterval. Values were swapped.");
} }
// Clamp ramp duration int globalIndex = 0;
if (difficultyRampDuration < 0.01f) difficultyRampDuration = 0.01f; for (int poolIdx = 0; poolIdx < _spawnConfig.obstaclePools.Length; poolIdx++)
{
ObstaclePool pool = _spawnConfig.obstaclePools[poolIdx];
if (pool == null || pool.obstacles == null || pool.obstacles.Length == 0)
{
Debug.LogWarning($"[ObstacleSpawner] Pool[{poolIdx}] is empty or null!");
continue;
}
// Clamp recency foreach (GameObject prefab in pool.obstacles)
if (recentDecayDuration < 0.01f) recentDecayDuration = 0.01f; {
if (minRecentWeight < 0f) minRecentWeight = 0f; if (prefab == null)
if (minRecentWeight > 1f) minRecentWeight = 1f; {
Debug.LogWarning($"[ObstacleSpawner] Null prefab found in pool[{poolIdx}]");
continue;
}
// Initialize last-used timestamps so prefabs start available (set to sufficiently negative so they appear with full weight) // Allow duplicates - same prefab can appear in multiple pools
int n = obstaclePrefabs != null ? obstaclePrefabs.Length : 0; if (!_obstacleToGlobalIndex.ContainsKey(prefab))
_lastUsedTimes = new float[n]; {
float initTime = -recentDecayDuration - 1f; _obstacleToGlobalIndex[prefab] = globalIndex;
for (int i = 0; i < n; i++) _lastUsedTimes[i] = initTime; _allObstacles.Add(prefab);
globalIndex++;
}
}
}
Debug.Log("[ObstacleSpawner] Initialized successfully"); // Initialize recency tracking
int totalObstacles = _allObstacles.Count;
_lastUsedTimes = new float[totalObstacles];
float initTime = Time.time - _spawnConfig.recentDecayDuration - 1f;
for (int i = 0; i < totalObstacles; i++)
{
_lastUsedTimes[i] = initTime;
}
// Log pool configuration
StringBuilder sb = new StringBuilder();
sb.AppendLine($"[ObstacleSpawner] Loaded {_spawnConfig.obstaclePools.Length} obstacle pools with {totalObstacles} unique obstacles:");
for (int i = 0; i < _spawnConfig.obstaclePools.Length; i++)
{
ObstaclePool pool = _spawnConfig.obstaclePools[i];
int obstacleCount = pool != null && pool.obstacles != null ? pool.obstacles.Length : 0;
float unlockTime = (i == 0) ? 0f : (_spawnConfig.poolUnlockTimes != null && i - 1 < _spawnConfig.poolUnlockTimes.Length ? _spawnConfig.poolUnlockTimes[i - 1] : -1f);
sb.AppendLine($" Pool[{i}]: {obstacleCount} obstacles, unlocks at {unlockTime}s");
}
Debug.Log(sb.ToString());
} }
private void Update() private void Update()
{ {
if (!isSpawning || spawnPoint == null) return; if (!_isSpawning || spawnPoint == null || _spawnConfig == null) return;
spawnTimer += Time.deltaTime; _spawnTimer += Time.deltaTime;
_elapsedTime += Time.deltaTime; _elapsedTime += Time.deltaTime;
if (spawnTimer >= _currentSpawnInterval) if (_spawnTimer >= _currentSpawnInterval)
{ {
SpawnObstacle(); SpawnObstacle();
spawnTimer = 0f; _spawnTimer = 0f;
// pick next interval based on difficulty ramp // Pick next interval based on difficulty ramp
float t = Mathf.Clamp01(_elapsedTime / difficultyRampDuration); float t = Mathf.Clamp01(_elapsedTime / _spawnConfig.difficultyRampDuration);
float difficulty = difficultyCurve.Evaluate(t); // 0..1 float difficulty = _spawnConfig.difficultyCurve.Evaluate(t); // 0..1
// map difficulty to interval: difficulty 0 -> max interval (easy), 1 -> min interval (hard) // Map difficulty to interval: difficulty 0 -> max interval (easy), 1 -> min interval (hard)
float baseInterval = Mathf.Lerp(maxSpawnInterval, minSpawnInterval, difficulty); float baseInterval = Mathf.Lerp(_spawnConfig.maxSpawnInterval, _spawnConfig.minSpawnInterval, difficulty);
// apply small jitter // Apply small jitter
if (intervalJitter > 0f) if (_spawnConfig.intervalJitter > 0f)
{ {
float jitter = Random.Range(-intervalJitter, intervalJitter); float jitter = Random.Range(-_spawnConfig.intervalJitter, _spawnConfig.intervalJitter);
_currentSpawnInterval = Mathf.Max(0f, baseInterval * (1f + jitter)); _currentSpawnInterval = Mathf.Max(0f, baseInterval * (1f + jitter));
} }
else else
@@ -167,14 +199,14 @@ namespace Minigames.BirdPooper
} }
/// <summary> /// <summary>
/// Spawn a random obstacle at the spawn point position (Y = 0). /// Spawn a random obstacle from currently unlocked pools at the spawn point position (Y = 0).
/// Uses timestamp/decay weighting so prefabs used recently are less likely. /// Uses timestamp/decay weighting so prefabs used recently are less likely.
/// </summary> /// </summary>
private void SpawnObstacle() private void SpawnObstacle()
{ {
if (obstaclePrefabs == null || obstaclePrefabs.Length == 0) if (_spawnConfig == null || _spawnConfig.obstaclePools == null || _spawnConfig.obstaclePools.Length == 0)
{ {
Debug.LogWarning("[ObstacleSpawner] No obstacle prefabs to spawn!"); Debug.LogWarning("[ObstacleSpawner] No obstacle pools configured!");
return; return;
} }
@@ -184,53 +216,133 @@ namespace Minigames.BirdPooper
return; return;
} }
int count = obstaclePrefabs.Length; // Determine which pools are currently unlocked based on elapsed time
int unlockedPoolCount = 1; // Pool[0] is always unlocked
// Defensive: ensure _lastUsedTimes is initialized and matches prefab count if (_spawnConfig.poolUnlockTimes != null)
if (_lastUsedTimes == null || _lastUsedTimes.Length != count)
{ {
_lastUsedTimes = new float[count]; for (int i = 0; i < _spawnConfig.poolUnlockTimes.Length; i++)
float initTime = Time.time - recentDecayDuration - 1f; {
for (int i = 0; i < count; i++) _lastUsedTimes[i] = initTime; if (_elapsedTime >= _spawnConfig.poolUnlockTimes[i])
{
unlockedPoolCount = i + 2; // +2 because we're unlocking pool[i+1]
}
else
{
break; // Times should be in order, so stop when we hit a future unlock
}
}
} }
// compute weights based on recency (newer = lower weight) // Clamp to available pools
float[] weights = new float[count]; unlockedPoolCount = Mathf.Min(unlockedPoolCount, _spawnConfig.obstaclePools.Length);
// Build list of available obstacles from unlocked pools
List<GameObject> availableObstacles = new List<GameObject>();
List<int> availableGlobalIndices = new List<int>();
for (int poolIdx = 0; poolIdx < unlockedPoolCount; poolIdx++)
{
ObstaclePool pool = _spawnConfig.obstaclePools[poolIdx];
if (pool == null || pool.obstacles == null) continue;
foreach (GameObject prefab in pool.obstacles)
{
if (prefab == null) continue;
// Add to available list (duplicates allowed if same prefab is in multiple pools)
availableObstacles.Add(prefab);
// Look up global index for recency tracking
if (_obstacleToGlobalIndex.TryGetValue(prefab, out int globalIdx))
{
availableGlobalIndices.Add(globalIdx);
}
else
{
Debug.LogWarning($"[ObstacleSpawner] Prefab '{prefab.name}' not found in global index!");
availableGlobalIndices.Add(-1); // Invalid index
}
}
}
if (availableObstacles.Count == 0)
{
Debug.LogWarning($"[ObstacleSpawner] No obstacles available in unlocked pools (0..{unlockedPoolCount-1})");
return;
}
// Compute weights based on recency
float[] weights = new float[availableObstacles.Count];
float now = Time.time; float now = Time.time;
for (int i = 0; i < count; i++)
for (int i = 0; i < availableObstacles.Count; i++)
{ {
float age = now - _lastUsedTimes[i]; int globalIdx = availableGlobalIndices[i];
float normalized = Mathf.Clamp01(age / recentDecayDuration); // 0 = just used, 1 = fully recovered if (globalIdx < 0 || globalIdx >= _lastUsedTimes.Length)
float weight = Mathf.Max(minRecentWeight, normalized); // ensure minimum probability {
weights[i] = weight; // base weight = 1.0, could be extended to per-prefab weights weights[i] = 1f; // Default weight for invalid indices
continue;
}
float age = now - _lastUsedTimes[globalIdx];
float normalized = Mathf.Clamp01(age / _spawnConfig.recentDecayDuration); // 0 = just used, 1 = fully recovered
float weight = Mathf.Max(_spawnConfig.minRecentWeight, normalized);
weights[i] = weight;
} }
// compute probabilities for logging // Compute and log probabilities for debugging
float totalW = 0f; float totalW = 0f;
for (int i = 0; i < count; i++) totalW += Mathf.Max(0f, weights[i]); for (int i = 0; i < availableObstacles.Count; i++)
{
totalW += Mathf.Max(0f, weights[i]);
}
if (totalW > 0f) if (totalW > 0f)
{ {
var sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.Append("[ObstacleSpawner] Prefab pick probabilities: "); sb.Append($"[ObstacleSpawner] Spawning from pools 0-{unlockedPoolCount-1}. Probabilities: ");
for (int i = 0; i < count; i++) for (int i = 0; i < availableObstacles.Count; i++)
{ {
float p = weights[i] / totalW; float p = weights[i] / totalW;
string name = obstaclePrefabs[i] != null ? obstaclePrefabs[i].name : i.ToString(); string prefabName = availableObstacles[i] != null ? availableObstacles[i].name : i.ToString();
sb.AppendFormat("{0}:{1:P1}", name, p); sb.AppendFormat("{0}:{1:P1}", prefabName, p);
if (i < count - 1) sb.Append(", "); if (i < availableObstacles.Count - 1) sb.Append(", ");
} }
Debug.Log(sb.ToString()); Debug.Log(sb.ToString());
} }
// Select obstacle using weighted random
int chosenIndex = WeightedPickIndex(weights); int chosenIndex = WeightedPickIndex(weights);
GameObject selectedPrefab = obstaclePrefabs[chosenIndex]; GameObject selectedPrefab = availableObstacles[chosenIndex];
int selectedGlobalIndex = availableGlobalIndices[chosenIndex];
// record usage timestamp // Record usage timestamp for recency tracking
_lastUsedTimes[chosenIndex] = Time.time; if (selectedGlobalIndex >= 0 && selectedGlobalIndex < _lastUsedTimes.Length)
{
_lastUsedTimes[selectedGlobalIndex] = Time.time;
}
// Determine which pool this obstacle came from (for logging)
int sourcePool = -1;
for (int poolIdx = 0; poolIdx < unlockedPoolCount; poolIdx++)
{
ObstaclePool pool = _spawnConfig.obstaclePools[poolIdx];
if (pool != null && pool.obstacles != null && System.Array.IndexOf(pool.obstacles, selectedPrefab) >= 0)
{
sourcePool = poolIdx;
break;
}
}
// Spawn at spawn point position with Y = 0 // Spawn at spawn point position with Y = 0
Vector3 spawnPosition = new Vector3(spawnPoint.position.x, 0f, 0f); Vector3 spawnPosition = new Vector3(spawnPoint.position.x, 0f, 0f);
GameObject obstacleObj = Instantiate(selectedPrefab, spawnPosition, Quaternion.identity); GameObject obstacleObj = Instantiate(selectedPrefab, spawnPosition, Quaternion.identity);
// Parent to container if provided
if (obstacleContainer != null)
{
obstacleObj.transform.SetParent(obstacleContainer, true);
}
// Initialize obstacle with despawn X position and EdgeAnchor references // Initialize obstacle with despawn X position and EdgeAnchor references
Obstacle obstacle = obstacleObj.GetComponent<Obstacle>(); Obstacle obstacle = obstacleObj.GetComponent<Obstacle>();
@@ -244,7 +356,7 @@ namespace Minigames.BirdPooper
Destroy(obstacleObj); Destroy(obstacleObj);
} }
Debug.Log($"[ObstacleSpawner] Spawned obstacle '{selectedPrefab.name}' at position {spawnPosition}"); Debug.Log($"[ObstacleSpawner] Spawned '{selectedPrefab.name}' from pool[{sourcePool}] at {spawnPosition}");
} }
private int WeightedPickIndex(float[] weights) private int WeightedPickIndex(float[] weights)
@@ -275,20 +387,45 @@ namespace Minigames.BirdPooper
/// <summary> /// <summary>
/// Start spawning obstacles. /// Start spawning obstacles.
/// Initializes the spawner if not already initialized, then begins spawning logic.
/// Spawns the first obstacle immediately, then continues with interval-based spawning. /// Spawns the first obstacle immediately, then continues with interval-based spawning.
/// </summary> /// </summary>
public void StartSpawning() public void StartSpawning()
{ {
isSpawning = true; // Initialize if not already done
spawnTimer = 0f; if (_spawnConfig == null)
{
Initialize();
}
// Ensure initialization was successful
if (_spawnConfig == null)
{
Debug.LogError("[ObstacleSpawner] Cannot start spawning - initialization failed!");
return;
}
// Begin the spawning process
BeginSpawningObstacles();
}
/// <summary>
/// Internal method that handles the actual spawning startup logic.
/// Sets initial state, computes first interval, and spawns the first obstacle.
/// </summary>
private void BeginSpawningObstacles()
{
_isSpawning = true;
_spawnTimer = 0f;
_elapsedTime = 0f; _elapsedTime = 0f;
// choose initial interval based on difficulty (at time 0) // Choose initial interval based on difficulty (at time 0)
float initialDifficulty = difficultyCurve.Evaluate(0f); float initialDifficulty = _spawnConfig.difficultyCurve.Evaluate(0f);
float initialBase = Mathf.Lerp(maxSpawnInterval, minSpawnInterval, initialDifficulty); float initialBase = Mathf.Lerp(_spawnConfig.maxSpawnInterval, _spawnConfig.minSpawnInterval, initialDifficulty);
if (intervalJitter > 0f)
if (_spawnConfig.intervalJitter > 0f)
{ {
float jitter = Random.Range(-intervalJitter, intervalJitter); float jitter = Random.Range(-_spawnConfig.intervalJitter, _spawnConfig.intervalJitter);
_currentSpawnInterval = Mathf.Max(0f, initialBase * (1f + jitter)); _currentSpawnInterval = Mathf.Max(0f, initialBase * (1f + jitter));
} }
else else
@@ -310,14 +447,14 @@ namespace Minigames.BirdPooper
/// </summary> /// </summary>
public void StopSpawning() public void StopSpawning()
{ {
isSpawning = false; _isSpawning = false;
Debug.Log("[ObstacleSpawner] Stopped spawning"); Debug.Log("[ObstacleSpawner] Stopped spawning");
} }
/// <summary> /// <summary>
/// Check if spawner is currently active. /// Check if spawner is currently active.
/// </summary> /// </summary>
public bool IsSpawning => isSpawning; public bool IsSpawning => _isSpawning;
#if UNITY_EDITOR #if UNITY_EDITOR
/// <summary> /// <summary>

View File

@@ -0,0 +1,153 @@
using UnityEngine;
using UnityEngine.UI;
using Core.Lifecycle;
using Pixelplacement.TweenSystem;
using Utils;
namespace Minigames.BirdPooper
{
/// <summary>
/// Manages "tap to start" flow for Bird Pooper minigame.
/// Shows blinking finger UI, waits for first tap, then starts the game.
/// </summary>
public class TapToStartController : ManagedBehaviour, ITouchInputConsumer
{
[Header("UI References")]
[SerializeField] private GameObject fingerContainer;
[SerializeField] private Image fingerImage;
[Header("Animation Settings")]
[Tooltip("Duration for one complete fade in/out cycle")]
[SerializeField] private float blinkDuration = 1.5f;
[Tooltip("Minimum alpha value during blink")]
[SerializeField] private float minAlpha = 0.3f;
[Tooltip("Maximum alpha value during blink")]
[SerializeField] private float maxAlpha = 1f;
private bool _isWaitingForTap;
private TweenBase _blinkTween;
internal override void OnManagedAwake()
{
base.OnManagedAwake();
// Validate references
if (fingerContainer == null)
{
Debug.LogError("[TapToStartController] Finger container not assigned!");
}
if (fingerImage == null)
{
Debug.LogError("[TapToStartController] Finger image not assigned!");
}
// Start hidden
if (fingerContainer != null)
{
fingerContainer.SetActive(false);
}
}
/// <summary>
/// Activates the tap-to-start UI and begins waiting for player input.
/// Called by BirdPooperGameManager when scene is ready.
/// </summary>
public void Activate()
{
if (_isWaitingForTap)
{
Debug.LogWarning("[TapToStartController] Already waiting for tap!");
return;
}
Debug.Log("[TapToStartController] Activating tap-to-start...");
_isWaitingForTap = true;
// Show finger UI
if (fingerContainer != null)
{
fingerContainer.SetActive(true);
}
// Start blinking animation using tween utility
if (fingerImage != null)
{
_blinkTween = TweenAnimationUtility.StartBlinkImage(fingerImage, minAlpha, maxAlpha, blinkDuration);
}
// Register as high-priority input consumer to catch first tap
if (Input.InputManager.Instance != null)
{
Input.InputManager.Instance.SetDefaultConsumer(this);
Debug.Log("[TapToStartController] Registered as input consumer");
}
else
{
Debug.LogError("[TapToStartController] InputManager instance not found!");
}
}
#region ITouchInputConsumer Implementation
public void OnTap(Vector2 tapPosition)
{
if (!_isWaitingForTap) return;
Debug.Log("[TapToStartController] First tap received! Starting game...");
// Stop waiting for tap
_isWaitingForTap = false;
// Stop blinking animation
if (_blinkTween != null)
{
_blinkTween.Stop();
_blinkTween = null;
}
// Hide finger UI
if (fingerContainer != null)
{
fingerContainer.SetActive(false);
}
// Unregister from input system
if (Input.InputManager.Instance != null)
{
Input.InputManager.Instance.SetDefaultConsumer(null);
Debug.Log("[TapToStartController] Unregistered from input");
}
// Tell game manager to start the game (it will handle the initial flap)
BirdPooperGameManager.Instance.BeginMinigame();
}
public void OnHoldStart(Vector2 position) { }
public void OnHoldMove(Vector2 position) { }
public void OnHoldEnd(Vector2 position) { }
#endregion
internal override void OnManagedDestroy()
{
// Stop blinking animation if active
if (_blinkTween != null)
{
_blinkTween.Stop();
_blinkTween = null;
}
// Unregister from input if still registered
if (_isWaitingForTap && Input.InputManager.Instance != null)
{
Input.InputManager.Instance.SetDefaultConsumer(null);
}
base.OnManagedDestroy();
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2a6ee5aca3ca423c82b57e16c0b2cca3
timeCreated: 1765922092

View File

@@ -31,9 +31,9 @@ namespace Minigames.BirdPooper
[Tooltip("Array of target prefabs to spawn randomly")] [Tooltip("Array of target prefabs to spawn randomly")]
[SerializeField] private GameObject[] targetPrefabs; [SerializeField] private GameObject[] targetPrefabs;
private IBirdPooperSettings settings; private IBirdPooperSettings _settings;
private float spawnTimer; private float _spawnTimer;
private bool isSpawning; private bool _isSpawning;
private float _currentTargetInterval = 1f; private float _currentTargetInterval = 1f;
[Header("Spawn Timing")] [Header("Spawn Timing")]
@@ -42,16 +42,17 @@ namespace Minigames.BirdPooper
[Tooltip("Maximum interval between target spawns (seconds)")] [Tooltip("Maximum interval between target spawns (seconds)")]
[SerializeField] private float maxTargetSpawnInterval = 2f; [SerializeField] private float maxTargetSpawnInterval = 2f;
internal override void OnManagedAwake() /// <summary>
/// Initializes the target spawner by loading settings and validating references.
/// Should be called once before spawning begins.
/// </summary>
private void Initialize()
{ {
base.OnManagedAwake();
// Load settings // Load settings
settings = GameManager.GetSettingsObject<IBirdPooperSettings>(); _settings = GameManager.GetSettingsObject<IBirdPooperSettings>();
if (settings == null) if (_settings == null)
{ {
Debug.LogError("[TargetSpawner] BirdPooperSettings not found!"); Debug.LogWarning("[TargetSpawner] BirdPooperSettings not found! Using inspector intervals.");
// continue we'll use inspector intervals
} }
// Validate interval range // Validate interval range
@@ -96,15 +97,15 @@ namespace Minigames.BirdPooper
private void Update() private void Update()
{ {
if (!isSpawning) if (!_isSpawning)
return; return;
spawnTimer += Time.deltaTime; _spawnTimer += Time.deltaTime;
if (spawnTimer >= _currentTargetInterval) if (_spawnTimer >= _currentTargetInterval)
{ {
SpawnTarget(); SpawnTarget();
spawnTimer = 0f; _spawnTimer = 0f;
// pick next random interval // pick next random interval
_currentTargetInterval = Random.Range(minTargetSpawnInterval, maxTargetSpawnInterval); _currentTargetInterval = Random.Range(minTargetSpawnInterval, maxTargetSpawnInterval);
} }
@@ -167,15 +168,34 @@ namespace Minigames.BirdPooper
} }
/// <summary> /// <summary>
/// Start spawning targets at regular intervals. /// Start spawning targets.
/// Initializes the spawner if not already initialized, then begins spawning logic.
/// </summary> /// </summary>
public void StartSpawning() public void StartSpawning()
{ {
isSpawning = true; // Initialize if not already done
spawnTimer = 0f; if (_settings == null)
// choose initial interval {
Initialize();
}
// Begin the spawning process
BeginSpawningTargets();
}
/// <summary>
/// Internal method that handles the actual spawning startup logic.
/// Sets initial state and computes first interval.
/// </summary>
private void BeginSpawningTargets()
{
_isSpawning = true;
_spawnTimer = 0f;
// Choose initial interval
_currentTargetInterval = Random.Range(minTargetSpawnInterval, maxTargetSpawnInterval); _currentTargetInterval = Random.Range(minTargetSpawnInterval, maxTargetSpawnInterval);
Debug.Log("[TargetSpawner] Started spawning targets");
Debug.Log($"[TargetSpawner] Started spawning targets with interval {_currentTargetInterval:F2}s");
} }
/// <summary> /// <summary>
@@ -183,14 +203,14 @@ namespace Minigames.BirdPooper
/// </summary> /// </summary>
public void StopSpawning() public void StopSpawning()
{ {
isSpawning = false; _isSpawning = false;
Debug.Log("[TargetSpawner] Stopped spawning targets"); Debug.Log("[TargetSpawner] Stopped spawning targets");
} }
/// <summary> /// <summary>
/// Check if spawner is currently spawning. /// Check if spawner is currently spawning.
/// </summary> /// </summary>
public bool IsSpawning => isSpawning; public bool IsSpawning => _isSpawning;
/// <summary> /// <summary>
/// Draw gizmos to visualize spawn and despawn points in the editor. /// Draw gizmos to visualize spawn and despawn points in the editor.

View File

@@ -1,4 +1,4 @@
using System; using System;
using Pixelplacement; using Pixelplacement;
using Pixelplacement.TweenSystem; using Pixelplacement.TweenSystem;
using UnityEngine; using UnityEngine;
@@ -145,6 +145,52 @@ namespace Utils
return Tween.CanvasGroupAlpha(canvasGroup, targetAlpha, duration, 0f, Tween.EaseInOut, completeCallback: onComplete); return Tween.CanvasGroupAlpha(canvasGroup, targetAlpha, duration, 0f, Tween.EaseInOut, completeCallback: onComplete);
} }
/// <summary>
/// Fade Image alpha
/// </summary>
public static TweenBase FadeImageAlpha(UnityEngine.UI.Image image, float targetAlpha, float duration, Action onComplete = null)
{
return Tween.Value(image.color.a, targetAlpha, (alpha) =>
{
if (image != null)
{
Color color = image.color;
color.a = alpha;
image.color = color;
}
}, duration, 0f, Tween.EaseInOut, completeCallback: onComplete);
}
/// <summary>
/// Start blinking animation on Image (ping-pong alpha fade)
/// </summary>
/// <param name="image">Image to blink</param>
/// <param name="minAlpha">Minimum alpha value</param>
/// <param name="maxAlpha">Maximum alpha value</param>
/// <param name="duration">Duration for one complete cycle (in and out)</param>
/// <returns>TweenBase that can be cancelled</returns>
public static TweenBase StartBlinkImage(UnityEngine.UI.Image image, float minAlpha = 0.3f, float maxAlpha = 1f, float duration = 1.5f)
{
// Set initial alpha to max
if (image != null)
{
Color color = image.color;
color.a = maxAlpha;
image.color = color;
}
// Create ping-pong tween (half duration for each direction)
return Tween.Value(maxAlpha, minAlpha, (alpha) =>
{
if (image != null)
{
Color color = image.color;
color.a = alpha;
image.color = color;
}
}, duration / 2f, 0f, Tween.EaseInOut, Tween.LoopType.PingPong);
}
/// <summary> /// <summary>
/// Pop-out with fade - scale to 0 and fade out simultaneously /// Pop-out with fade - scale to 0 and fade out simultaneously
/// </summary> /// </summary>

View File

@@ -20,7 +20,60 @@ MonoBehaviour:
maxRotationAngle: 40 maxRotationAngle: 40
rotationSpeed: 18 rotationSpeed: 18
obstacleMoveSpeed: 7 obstacleMoveSpeed: 7
obstacleSpawnInterval: 0.1 obstacleSpawnConfiguration:
obstaclePools:
- obstacles:
- {fileID: 8855270423038321603, guid: 20ae02a8f50484045aaf3dcee33fb9a2, type: 3}
- {fileID: 2514399078413048981, guid: ee834e7efcf7d8749881f71f8b0da99c, type: 3}
- {fileID: 842802843766402460, guid: cdc806fd167bba3488797031a28657fa, type: 3}
- {fileID: 4239333156730914246, guid: 332d8cce2ed99054c83ecf84fbfa14c8, type: 3}
- {fileID: 6660502783540694524, guid: 5d42fc70e5838544ab654e30aa4b0c48, type: 3}
- {fileID: 2421410811796775077, guid: 371a09b68a5c0654bac9ba58ad3bcbe5, type: 3}
- obstacles:
- {fileID: 1408173265900928789, guid: 871373a85e5da0e4cafdf0e47496e105, type: 3}
- {fileID: 1408173265900928789, guid: d2998934362713545a040d7017a1bd36, type: 3}
- {fileID: 1408173265900928789, guid: 146d99398c0e7964dbed504e256adab7, type: 3}
- {fileID: 1408173265900928789, guid: dc8a19e9a4d30b44596237d915b3b73f, type: 3}
- {fileID: 1408173265900928789, guid: 471f367e14f9cfb4fb2c40d799d4c292, type: 3}
- {fileID: 1408173265900928789, guid: 5f1734c5705cdfd49ae3180d678d28b3, type: 3}
- obstacles:
- {fileID: 1408173265900928789, guid: 6bc84c3ea9854b54f85a8fb69c769790, type: 3}
- {fileID: 1408173265900928789, guid: 166c7e1bfcc4c854fab0af51cdfff746, type: 3}
- {fileID: 1408173265900928789, guid: 65810bfd58ebbaf4482527452258ae50, type: 3}
- {fileID: 1408173265900928789, guid: ae3986a7db087c845b618a9c897705ec, type: 3}
poolUnlockTimes:
- 20
- 40
minSpawnInterval: 1
maxSpawnInterval: 2
difficultyRampDuration: 60
difficultyCurve:
serializedVersion: 2
m_Curve:
- serializedVersion: 3
time: 0
value: 0
inSlope: 0
outSlope: 1
tangentMode: 0
weightedMode: 0
inWeight: 0
outWeight: 0
- serializedVersion: 3
time: 1
value: 1
inSlope: 1
outSlope: 0
tangentMode: 0
weightedMode: 0
inWeight: 0
outWeight: 0
m_PreInfinity: 2
m_PostInfinity: 2
m_RotationOrder: 4
intervalJitter: 0.05
recentDecayDuration: 10
minRecentWeight: 0.1
obstacleSpawnXPosition: 12 obstacleSpawnXPosition: 12
obstacleDestroyXPosition: -12 obstacleDestroyXPosition: -12
obstacleMinSpawnY: -3 obstacleMinSpawnY: -3

View File

@@ -28,18 +28,24 @@ MonoBehaviour:
forceDeviation: 0.3 forceDeviation: 0.3
thinkTimeMin: 0.5 thinkTimeMin: 0.5
thinkTimeMax: 1 thinkTimeMax: 1
trashBagDetonationDistanceMin: 0.3
trashBagDetonationDistanceMax: 0.5
- difficulty: 1 - difficulty: 1
data: data:
angleDeviation: 30 angleDeviation: 30
forceDeviation: 0.2 forceDeviation: 0.2
thinkTimeMin: 0.2 thinkTimeMin: 0.2
thinkTimeMax: 0.8 thinkTimeMax: 0.8
trashBagDetonationDistanceMin: 0.2
trashBagDetonationDistanceMax: 0.4
- difficulty: 2 - difficulty: 2
data: data:
angleDeviation: 10 angleDeviation: 10
forceDeviation: 0.1 forceDeviation: 0.1
thinkTimeMin: 0.2 thinkTimeMin: 0.2
thinkTimeMax: 0.8 thinkTimeMax: 0.8
trashBagDetonationDistanceMin: 0.1
trashBagDetonationDistanceMax: 0.5
defaultAIDifficulty: 1 defaultAIDifficulty: 1
aiAllowedProjectiles: 000000000100000003000000 aiAllowedProjectiles: 000000000100000003000000
weakPointExplosionRadius: 6 weakPointExplosionRadius: 6