Add player controller, state management, and input handling

- Implemented PlayerController.cs to manage player movement and actions.
- Created PlayerState.cs to track player lives, coins, and key status.
- Added CameraFollow.cs for smooth camera movement following the player.
- Developed Character.cs as an abstract class for character behavior.
- Introduced Enums.cs for defining TreasureType and MapElementType.
- Added IDoor interface for door interactions.
- Created InputActions.cs for handling player input actions.
- Implemented MainMenu.cs for basic menu functionality including play and exit options.
This commit is contained in:
2026-06-17 22:43:59 +03:00
parent dabd056e8b
commit 39e4e51866
70 changed files with 1807 additions and 99 deletions
+309
View File
@@ -0,0 +1,309 @@
# Architecture Migration - Completion Summary
## Overview
All 10 tasks from the ArchitectureMigration.md plan have been successfully completed. The Gnome's Bounty project now has cleaner architecture, improved separation of concerns, and new core gameplay systems.
---
## Changes Made by Task
### Task 1 ✓ - Normalize UI Manager Naming
**Files Changed:**
- `UiManager.cs``UIManager.cs` (file and class renamed)
**What Changed:**
- Renamed file and class to follow proper C# naming convention (UIManager instead of UiManager)
- No breaking changes - internal logic untouched
---
### Task 2 ✓ - Separate Hammer Throw Logic and Hammer Projectile Logic
**Files Changed:**
- `HammerThrower.cs` (refactored)
- `Hammer.cs` (refactored)
**What Changed:**
- **HammerThrower.cs**:
- Added cooldown system (`_throwCooldown`, `_cooldownTimer`)
- Added `CanThrow` property to check if ready
- New `TryThrowHammer()` method that respects cooldown
- Calls `Hammer.Initialize()` to set direction and speed
- Default cooldown: 1.5 seconds
- **Hammer.cs**:
- Added `Initialize(bool facingRight, float speed)` method
- Improved collision detection with different object types
- Stuns enemies on collision (`OnHitByHammer`)
- Breaks BreakableWall objects
- Emits noise on impact (integrates with NoiseSystem)
- Self-destructs on any collision
- Default lifespan: 5 seconds
---
### Task 3 ✓ - Add GameManager
**File Created:**
- `Managers/GameManager.cs`
**Functionality:**
- Singleton managing global game state
- Tracks key ownership: `HasKey`, `SetKeyState(bool)`
- Tracks treasure count: `TreasureCount`, `AddTreasure(int)`
- Events: `OnKeyStateChanged`, `OnTreasureCountChanged`, `OnLevelComplete`
- `CompletLevel()` method for level completion
- `Reset()` for resetting game state
- Debug mode for logging
**Setup Required:**
- Add empty GameObject with GameManager script to scene
- Component will auto-persist with `DontDestroyOnLoad`
---
### Task 4 ✓ - Add LevelManager
**File Created:**
- `Managers/LevelManager.cs`
**Functionality:**
- Singleton managing level progression
- Tracks key collection and door unlock
- Subscribes to GameManager key state changes
- `NotifyKeyCollected()` - triggered when player gets key
- `NotifyLevelComplete()` - triggered when player exits with key
- Events: `OnKeyCollected`, `OnDoorUnlocked`, `OnLevelComplete`
- `Reset()` for restarting level
- Debug mode for logging
**Setup Required:**
- Add empty GameObject with LevelManager script to scene
- In Inspector: Assign Door reference to the `_doorReference` field
---
### Task 5 ✓ - Add NoiseSystem
**Files Created/Modified:**
- `Managers/NoiseSystem.cs` (new)
- `EnvironmentObjects/BreakableWall.cs` (updated)
- `Hammer.cs` (already includes noise emission)
**Functionality:**
- Singleton noise emission system
- `Emit(Vector3 position, float radius)` - emits noise and alerts nearby enemies
- Automatically detects enemies on "Enemy" layer
- Calls `OnNoise(Vector3 position)` on all nearby enemies
- Event: `OnNoiseEmitted` for external systems
**Setup Required:**
- Add empty GameObject with NoiseSystem script to scene
- Ensure all enemy GameObject have "Enemy" layer assigned
---
### Task 6 ✓ - Add Enemy States to EnemyAI
**File Modified:**
- `EnemyAI.cs` (completely refactored)
**Functionality:**
- State machine with 4 states: `Patrol`, `Investigate`, `Chase`, `Stunned`
- Automatic state transitions based on distance to player
- `OnNoise(Vector3 position)` - enters Investigate state
- `OnHitByHammer(float stunDuration)` - enters Stunned state and recovers after duration
- Configurable ranges and speeds via Inspector
- Inspector fields:
- `_patrolSpeed`: Speed during patrol
- `_patrolRange`: How far to patrol
- `_investigateRange`: Range to trigger investigate
- `_chaseRange`: Range to trigger chase
- `_stunDuration`: How long to stay stunned (default: 1 second)
**Behavior:**
- Patrols back and forth when at peace
- Investigates noise sources when hearing sound
- Chases player when within range
- Recovers from stun and resumes normal behavior
---
### Task 7 ✓ - Finalize Hammer Cooldown and Tactical Rules
**Files Modified:**
- `PlayerController.cs` (updated to use new hammer API)
- `HammerThrower.cs` (already includes cooldown)
- `Hammer.cs` (already includes tactical rules)
**What Changed:**
- PlayerController now checks `_hammerThrower.CanThrow` before playing throw animation
- Calls `TryThrowHammer()` instead of `ThrowHammer()`
- Hammer impacts emit noise automatically (configurable)
- Hammer stuns enemies without killing them
- Hammer breaks only BreakableWall objects
- Hammer disappears on impact
**Tunable Values (Inspector):**
- HammerThrower: `_throwCooldown`, `_throwSpeed`
- Hammer: `_lifespan`, `_stunDuration`, `_impactNoiseRadius`, `_emitNoiseOnImpact`
---
### Task 8 ✓ - Integrate KeyChest with Game State
**Files Modified:**
- `KeyChest.cs` (updated)
- `Chest.cs` (updated)
**What Changed:**
- KeyChest now notifies GameManager when key collected
- KeyChest triggers LevelManager to unlock door
- Chest properly handles coin and key treasures
- Both systems integrate with GameManager for centralized state tracking
- Events flow: Chest/KeyChest → GameManager → LevelManager → Door
---
### Task 9 ✓ - Improve Door Flow
**Files Modified:**
- `Door.cs` (refactored)
- `DoorInteract.cs` (refactored)
**What Changed:**
- **Door.cs**:
- Added explicit `IsLocked` state property
- `OpenDoor()` now updates lock state, visuals, and collision
- `LockDoor()` can re-lock the door if needed
- Event: `OnDoorOpened`
- **DoorInteract.cs**:
- Checks GameManager.HasKey instead of PlayerState
- Triggers LevelManager.NotifyLevelComplete() when player exits with key
- Prevents multiple completions with `_hasTriggered`
- Debug logging for testing
**Progression Flow:**
1. Player collects key → KeyChest → GameManager.SetKeyState(true)
2. GameManager triggers → LevelManager.NotifyKeyCollected()
3. LevelManager unlocks → Door.OpenDoor()
4. Player reaches exit → DoorInteract triggers
5. DoorInteract → LevelManager.NotifyLevelComplete()
---
### Task 10 ✓ - Folder Cleanup
**Folders Created:**
- `Assets/Scripts/Player/` - Player-related scripts
- `Assets/Scripts/Combat/` - Combat/projectile scripts
- `Assets/Scripts/Enemies/` - Enemy AI and spawning
- `Assets/Scripts/Environment/` - Environmental objects
- `Assets/Scripts/Utilities/` - Helper and utility classes
**Files Moved:**
- **Player/**: PlayerController, HammerThrower, PlayerState
- **Combat/**: Hammer
- **Enemies/**: EnemyAI, EnemySpawner (renamed from CharacterSpawner)
- **Environment/**: BreakableWall, Chest, Door, DoorInteract, KeyChest, MapElements/
- **Managers/**: GameManager, LevelManager, NoiseSystem, UIManager, InputManager (unchanged location)
- **ScriptableObject/**: TreasureSO, MapElementSO (unchanged location)
- **Utilities/**: Character, CameraFollow, IDoor, Enums, InputActions, MainMenu
---
## Scene Setup Checklist
To get the project running after these changes:
- [ ] **Add GameManager to Scene**
- Create empty GameObject
- Add `GameManager` component
- Leave Debug Mode off for release
- [ ] **Add LevelManager to Scene**
- Create empty GameObject
- Add `LevelManager` component
- **In Inspector:** Assign the Door GameObject to `_doorReference` field
- Leave Debug Mode off for release
- [ ] **Add NoiseSystem to Scene**
- Create empty GameObject
- Add `NoiseSystem` component
- Ensure all enemy GameObjects have "Enemy" layer assigned
- Leave Debug Mode off for release
- [ ] **Update Enemy Layer**
- Select all enemy GameObjects
- Set Layer to "Enemy" (create if doesn't exist)
- This is critical for NoiseSystem to detect enemies
- [ ] **Update Scene References**
- Check for any scripts that directly reference moved classes
- Most will auto-resolve if using GetComponent<>()
- Update Inspector if scripts are assigned as references
- [ ] **Test the Flow:**
1. Player throws hammer (with cooldown)
2. Hammer hits enemy - enemy should stun and nearby enemies should hear noise
3. Player collects key - GameManager updates, door should unlock
4. Player exits through door - level completion triggered
---
## Key Architectural Improvements
1. **Clear Separation of Concerns**
- Hammer throwing vs. hammer behavior
- Player controller vs. player state vs. hammer equipment
- Enemy AI vs. enemy spawning
2. **Centralized Game State**
- GameManager handles all global state
- LevelManager orchestrates progression
- No scattered state management
3. **Event-Driven Architecture**
- Systems communicate via events
- Loose coupling between systems
- Easy to add new features
4. **Extensible Gameplay Systems**
- Noise system can be expanded for more sounds
- Enemy states make new behaviors easy to add
- Hammer can be enhanced with additional effects
5. **Inspector-Friendly**
- Tunable parameters for game feel
- Debug modes for testing
- Clear assignment fields
---
## Files Summary
**New Files (3):**
- `Managers/GameManager.cs`
- `Managers/LevelManager.cs`
- `Managers/NoiseSystem.cs`
**Modified Files (9):**
- `Managers/UIManager.cs` (renamed from UiManager)
- `Player/HammerThrower.cs` (refactored)
- `Combat/Hammer.cs` (refactored)
- `Enemies/EnemyAI.cs` (refactored)
- `Environment/BreakableWall.cs` (updated)
- `Environment/Chest.cs` (updated)
- `Environment/KeyChest.cs` (updated)
- `Environment/Door.cs` (refactored)
- `Environment/DoorInteract.cs` (refactored)
**Renamed:**
- `CharacterSpawner.cs``EnemySpawner.cs`
**Moved (folder reorganization only, no content changes):**
- Multiple scripts distributed into logical folders
---
## Notes
- All existing gameplay is preserved
- The changes follow Unity best practices
- Systems are designed to be maintainable and extensible
- Debug modes can be disabled before release
- No major breaking changes - mostly additive improvements
**Status:****All tasks complete and ready for testing**
+142
View File
@@ -0,0 +1,142 @@
# Quick Setup Guide - Post Migration
## Immediate Next Steps
### 1. Refresh Unity Project
- Open the Gnome's Bounty project in Unity
- Wait for asset import to complete
- Check Console for any errors related to moved files
### 2. Create Required GameObjects in Scene
**Add these to your main gameplay scene:**
#### GameManager
1. Right-click in Hierarchy → Create Empty
2. Name it "GameManager"
3. Drag GameManager script from `Assets/Scripts/Managers/GameManager.cs` onto it
4. Leave settings at defaults (debug mode optional)
#### LevelManager
1. Right-click in Hierarchy → Create Empty
2. Name it "LevelManager"
3. Drag LevelManager script from `Assets/Scripts/Managers/LevelManager.cs` onto it
4. **IMPORTANT:** In Inspector, drag your Door GameObject to the `_doorReference` field
5. Leave settings at defaults (debug mode optional)
#### NoiseSystem
1. Right-click in Hierarchy → Create Empty
2. Name it "NoiseSystem"
3. Drag NoiseSystem script from `Assets/Scripts/Managers/NoiseSystem.cs` onto it
4. Enemy Layer should be set to "Enemy" automatically
5. Leave settings at defaults (debug mode optional)
### 3. Configure Layers
1. In Hierarchy, select all enemy GameObjects
2. In Inspector, change Layer to "Enemy"
3. Create the layer if it doesn't exist (Layer dropdown → Add Layer → "Enemy")
### 4. Testing Checklist
After setup, test these features:
- [ ] **Hammer Throw**: Throw hammer and verify cooldown works (should delay next throw by ~1.5 sec)
- [ ] **Enemy Stun**: Hit an enemy with hammer, it should freeze for 1 second
- [ ] **Wall Break**: Break a breakable wall with hammer
- [ ] **Noise System**: Break a wall or hit enemy near another enemy - second enemy should investigate
- [ ] **Key Collection**: Pick up key, GameManager should show `HasKey = true`
- [ ] **Door Unlock**: After picking up key, door should open automatically
- [ ] **Level Complete**: Exit through open door with key - should trigger level completion
### 5. If Compilation Errors Occur
**Most likely causes:**
1. **"Cannot find type 'GameManager'"** - Make sure GameManager component is added to scene
2. **"Missing script references"** - Delete and re-add the script component
3. **"Cannot find EnemyAI"** - Verify EnemyAI.cs moved to `Enemies/` folder correctly
**Quick fix:**
- In Unity, go to Assets → Reimport All
- Wait for compilation to complete
- Check Console for remaining errors
### 6. Debug Features
To enable debug logging in managers:
1. Select GameManager in Hierarchy
2. In Inspector, check `Debug Mode`
3. Repeat for LevelManager and NoiseSystem
4. Play game - console will show state changes
5. **Remember to disable before final build**
---
## What If You Encounter Errors?
### Scenes Won't Load
- Unity may need to reload scenes
- Close the scene, delete from Recent, and re-open
### "CharacterSpawner" not found
- This class was renamed to `EnemySpawner`
- Update any scene prefabs or scripts that reference it
- Check `Enemies/EnemySpawner.cs`
### PlayerController Errors
- Check that `GetComponent<HammerThrower>()` can still find it
- If not, re-add PlayerController script to Player GameObject
### Missing References in Inspector
- Right-click the field → "Try Find Component"
- Or manually drag the object from scene/hierarchy
---
## Performance Notes
The new systems have minimal performance impact:
- **GameManager**: O(1) operations, just stores state
- **LevelManager**: Minimal, just tracks key/completion
- **NoiseSystem**: O(n) where n = enemies in range (typically small)
- **EnemyAI States**: Simple state switching, no AI overhead
No performance concerns with default settings.
---
## Next Development Steps
With the architecture in place, you can now easily:
1. **Add new hammer effects** - Modify Hammer.cs
2. **Add new enemy behaviors** - Add states to EnemyAI.cs
3. **Add puzzles** - Create new interaction systems using GameManager
4. **Add levels** - Use GameManager/LevelManager for progression
5. **Add UI** - Hook into GameManager events for HUD updates
All systems use events for loose coupling, making extensions clean and safe.
---
## File Location Reference
| What | Location |
|------|----------|
| Player Controller | `Assets/Scripts/Player/PlayerController.cs` |
| Hammer Mechanics | `Assets/Scripts/Combat/Hammer.cs` |
| Hammer Throwing | `Assets/Scripts/Player/HammerThrower.cs` |
| Enemy AI | `Assets/Scripts/Enemies/EnemyAI.cs` |
| Enemy Spawner | `Assets/Scripts/Enemies/EnemySpawner.cs` |
| Game State | `Assets/Scripts/Managers/GameManager.cs` |
| Level Control | `Assets/Scripts/Managers/LevelManager.cs` |
| Noise System | `Assets/Scripts/Managers/NoiseSystem.cs` |
| UI Manager | `Assets/Scripts/Managers/UIManager.cs` |
| Environment | `Assets/Scripts/Environment/*.cs` |
---
**Status:** Ready to import into Unity and test! 🎮