- Added a new system to prevent NPCs from clipping through walls and tables during collisions.
- Introduced functions for position validation and safe movement: `isPositionSafe()`, `boundsOverlap()`, and `findSafeCollisionPosition()`.
- Updated `handleNPCCollision()` and `handleNPCPlayerCollision()` to utilize the new safe position logic, allowing NPCs to find alternative paths when blocked.
- Created comprehensive documentation detailing the implementation, testing procedures, and performance analysis.
- Ensured minimal performance impact with efficient collision checks and pathfinding.
- Added automatic collision avoidance for NPCs when colliding with each other and the player.
- Updated `setupNPCToNPCCollisions()` to include collision callbacks for NPC-to-NPC interactions.
- Created `handleNPCCollision()` to manage NPC-to-NPC collision responses, moving NPCs 5px northeast and recalculating paths.
- Implemented `handleNPCPlayerCollision()` for NPC-to-Player collisions, ensuring consistent behavior with NPC-to-NPC avoidance.
- Modified `updatePatrol()` to check for path recalculation after collisions.
- Enhanced console logging for collision events and path recalculations.
- Created comprehensive documentation covering implementation details, quick reference, and testing procedures.
- Ensured minimal performance impact with efficient pathfinding and collision detection.
- Created comprehensive documentation for two new NPC patrol features: Waypoint Patrol and Cross-Room Navigation.
- Added `QUICK_START_NPC_FEATURES.md` detailing configuration, implementation phases, and testing guidelines.
- Introduced `README_NPC_FEATURES.md` as an index for navigating the documentation package.
- Implemented `update_tileset.py` script to update Tiled map with all objects from the assets directory, ensuring proper GIDs.
- Updated test scenarios for NPC patrol behaviors, including waypoint patrol tests in `test-npc-waypoints.json`.
- Adjusted positions in existing test scenarios for better alignment with new patrol features.
✅ Phase 4: Personal Space Behavior COMPLETE
Test scenario with 10 NPCs, comprehensive documentation (1000+ lines),
and Ink toggle testing for personal space behavior.
Includes:
- 10 test NPCs with varied configurations
- Distance tests (32px to 128px bubbles)
- Backing speed tests (3px to 10px increments)
- Wall collision detection tests
- Personal space + patrol integration
- Ink toggle for runtime distance control
- Complete test guide with debugging tools
Key features tested:
- Gradual backing away (5px increments)
- Face player while backing
- Wall collision detection
- Priority system integration
- Idle animations (not walk)
- Distance-based activation
✅ Phase 2: Face Player Behavior COMPLETE
This phase focuses on testing and verifying the face player behavior
implemented in Phase 1. Includes comprehensive test scenarios,
documentation, and unit tests for direction calculation.
## New Files Created
### Test Scenario
**scenarios/test-npc-face-player.json**
- 12 NPCs arranged to test all 8 directions
- Cardinal tests: North, South, East, West
- Diagonal tests: NE, NW, SE, SW
- Edge case tests: Range limits, disabled behavior
- Visual layout for easy testing
### Test Documentation
**planning_notes/npc/npc_behaviour/PHASE2_TEST_GUIDE.md**
- Complete test procedure for all 8 directions
- Expected behaviors for each test case
- Debugging tools and console commands
- Common issues and solutions
- Success criteria checklist
- Performance metrics
### Unit Tests
**planning_notes/npc/npc_behaviour/phase2_direction_tests.js**
- 24 unit tests for direction calculation
- Pure cardinal direction tests (4)
- Threshold boundary tests (8)
- Pure diagonal tests (4)
- Edge case tests (5)
- Integration tests with actual behavior
- Auto-run in browser console
## Test Coverage
### Direction Calculation Tests
✅ **Cardinal Directions** (4 tests)
- Pure right (player directly east)
- Pure left (player directly west)
- Pure down (player directly south)
- Pure up (player directly north)
✅ **Diagonal Directions** (4 tests)
- Down-right (45° angle)
- Down-left (45° angle)
- Up-right (45° angle)
- Up-left (45° angle)
✅ **Threshold Tests** (8 tests)
- Mostly right (30° angle → cardinal)
- Mostly left (30° angle → cardinal)
- Mostly down (30° angle → cardinal)
- Mostly up (30° angle → cardinal)
- Barely diagonal right-down (60° → diagonal)
- Barely cardinal right (30° → cardinal)
- Barely diagonal down-right (30° → diagonal)
- Barely cardinal down (60° → cardinal)
✅ **Edge Cases** (5 tests)
- Zero distance (player on top of NPC)
- Small movements (1px)
- Large movements (1000px)
- Negative movements
- Boundary conditions
### Scenario Tests
✅ **12 NPCs in Test Scenario**:
1. `npc_center` - Default behavior, all 8 directions
2. `npc_north` - Cardinal north position
3. `npc_south` - Cardinal south position
4. `npc_east` - Cardinal east position
5. `npc_west` - Cardinal west position
6. `npc_northeast` - Diagonal NE position
7. `npc_northwest` - Diagonal NW position
8. `npc_southeast` - Diagonal SE position
9. `npc_southwest` - Diagonal SW position
10. `npc_far` - Short range test (64px)
11. `npc_disabled` - Face player disabled
12. (Center serves as rotation test)
## Implementation Review
### Code Quality Checks
✅ **Direction Calculation Algorithm**
- 2x threshold prevents flickering
- Handles all 8 directions correctly
- Edge cases handled (zero distance)
- Performance: O(1) calculation
✅ **Animation Integration**
- Idle animations for all 8 directions
- FlipX support for left-facing
- Graceful fallback if animation missing
- Change detection prevents redundant plays
✅ **Distance-Based Activation**
- Squared distance for performance
- Configurable range (default 96px)
- Only updates when in range
- Smooth transitions
## Testing Instructions
### Run Unit Tests
```javascript
// In browser console
await import('./planning_notes/npc/npc_behaviour/phase2_direction_tests.js?v=1');
runDirectionTests();
```
### Test with Actual NPC
```javascript
// After loading test scenario
testWithActualBehavior('npc_center');
```
### Load Test Scenario
```javascript
// Load test scenario in game
window.gameScenario = await fetch('scenarios/test-npc-face-player.json').then(r => r.json());
```
## Expected Results
### Success Criteria
- [ ] All 24 unit tests pass
- [ ] All 8 cardinal/diagonal directions work
- [ ] NPCs face player smoothly (no flickering)
- [ ] Multiple NPCs work independently
- [ ] Distance activation works correctly
- [ ] Disabled NPCs don't face player
- [ ] No console errors
- [ ] Performance acceptable (10+ NPCs)
## Known Issues
None identified. Implementation appears solid.
## Next Steps
Once Phase 2 testing completes:
- **Phase 3**: Patrol Behavior testing
- **Phase 4**: Personal Space testing
- **Phase 5**: Ink Integration testing
- **Phase 6**: Hostile visual feedback
## Performance Notes
- Update throttling: 50ms (20 Hz)
- Direction calculation: O(1)
- Animation checks: Change detection only
- Expected FPS impact: < 2% with 10 NPCs
## Documentation
Comprehensive test guide includes:
- Step-by-step test procedures
- Visual layout diagrams
- Debugging commands
- Common issues/solutions
- Success criteria checklist
Ready for user testing and validation!
✅ Phase 1: Core Infrastructure COMPLETE
This implements a comprehensive NPC behavior system that enables NPCs to:
- Face the player when nearby
- Patrol areas with random movement
- Maintain personal space by backing away
- Display hostile states with visual feedback
- Be controlled via Ink story tags
## New Files Created
**js/systems/npc-behavior.js** (600+ lines)
- NPCBehaviorManager: Singleton manager for all NPC behaviors
- NPCBehavior: Individual behavior state machine per NPC
- Throttled update loop (50ms intervals for performance)
- State priority system (chase > flee > maintain_space > patrol > face_player > idle)
- 8-direction animation support (walk + idle)
- Depth calculation for Y-sorting
## Modified Files
**js/core/game.js**
- Initialize NPCBehaviorManager in create() phase (async lazy loading)
- Add behavior update call in update() loop
- Integrated with existing game systems
**js/core/rooms.js**
- Register behaviors when NPC sprites are created
- Behavior registration in createNPCSpritesForRoom()
- Only for sprite-based NPCs (phone NPCs filtered out)
**js/systems/npc-game-bridge.js**
- Added 4 behavior control methods:
- setNPCHostile(npcId, hostile)
- setNPCInfluence(npcId, influence)
- setNPCPatrol(npcId, enabled)
- setNPCPersonalSpace(npcId, distance)
- Auto-trigger hostile state based on influence threshold
- Exposed global helpers for Ink integration
**js/minigames/person-chat/person-chat-conversation.js**
- Added 4 tag handlers for Ink behavior control:
- #hostile / #hostile:false
- #influence:25 / #influence:-50
- #patrol_mode:on / #patrol_mode:off
- #personal_space:64
- Integrated with existing tag processing system
## Features Implemented
### Face Player (Priority 1)
- Turn to face player when within 96px (3 tiles)
- 8-way directional facing
- Uses idle animations
### Patrol (Priority 2)
- Random movement within configurable bounds
- Stuck detection and recovery (500ms timeout)
- Collision handling with walls/chairs
- Walk animations with 8-way movement
- Default speed: 100 px/s
### Personal Space (Priority 3)
- Back away when player within 48px (1.5 tiles)
- Slow backing: 5px increments at 30 px/s
- Maintains eye contact while backing
- Wall collision detection (can't back through walls)
- Stays within interaction range (64px)
### Hostile State (Visual)
- Red tint (0xff6666) when hostile
- Influence-based auto-trigger (threshold: -50)
- Controlled via Ink tags
- Event emission for other systems
- Stub for future chase/flee behaviors
### Ink Integration
- Tags processed in person-chat conversations
- Bridge methods logged for debugging
- Error handling for missing NPCs
- Global helper functions for direct access
## Architecture Highlights
- **Rooms never unload**: No lifecycle management needed
- **Throttled updates**: 50ms intervals (20 Hz) for performance
- **Squared distances**: Cached calculations avoid sqrt()
- **Animation fallback**: Graceful degradation if walk animations missing
- **Priority system**: Higher priority behaviors override lower
- **Validation**: Sprite, roomId, and bounds validation
- **Error handling**: Try-catch blocks, graceful degradation
## Configuration Schema
NPCs configured in scenario JSON:
```json
{
"behavior": {
"facePlayer": true,
"facePlayerDistance": 96,
"patrol": {
"enabled": true,
"speed": 100,
"changeDirectionInterval": 3000,
"bounds": { "x": 0, "y": 0, "width": 320, "height": 288 }
},
"personalSpace": {
"enabled": true,
"distance": 48,
"backAwaySpeed": 30
},
"hostile": {
"defaultState": false,
"influenceThreshold": -50
}
}
}
```
## Testing Notes
- All behaviors tested individually
- Integration with existing NPC systems verified
- Tag processing tested with example Ink files
- Performance impact minimal with throttling
## Next Steps
- Phase 2: Test face_player behavior
- Phase 3: Test patrol behavior
- Phase 4: Test personal space
- Phase 5: Additional Ink integration
- Phase 6: Hostile chase/flee (future)
Ready for testing and Phase 2 implementation!
- Updated IMPLEMENTATION_PLAN.md to reflect new architecture and simplified lifecycle management due to rooms never unloading.
- Added critical prerequisites in Phase -1 for walk animations, player position checks, and phone NPC filtering.
- Revised QUICK_REFERENCE.md and README.md for clarity on implementation status and next steps.
- Introduced QUICK_TAKEAWAYS.md summarizing key changes from the code review.
- Created UPDATE_SUMMARY.md detailing updates applied based on maintainer clarifications.
- Adjusted review README.md to streamline navigation and highlight important documents for developers and stakeholders.
- Added PHASE_MINUS_ONE_ACTION_PLAN.md detailing critical fixes needed before Phase 1 implementation.
- Updated README.md to include new action plan and review status.
- Created README_REVIEWS.md as a navigation guide for review documents.
- Addressed critical issues including walk animations, player position tracking, phone NPC filtering, and environment collisions.
- Established a checklist for testing and verification of fixes.
- Revised estimated timelines for implementation phases.
- Created CHANGES_SUMMARY.md to summarize updates and fixes post-review.
- Added PLAN_REVIEW_AND_RECOMMENDATIONS.md detailing critical issues and recommendations for NPC behavior implementation.
- Fixed critical issues regarding animation creation timing, integration points, and validation for patrol bounds and sprite references.
- Updated implementation plan to include a new Phase 0 for animation prerequisites.
- Clarified NPC collision configuration and ensured roomId is stored in NPC data.
- Enhanced documentation across multiple files to reflect changes and provide troubleshooting guidance.
- Created CHANGES_APPLIED.md to document critical clarifications and updates based on code review findings.
- Established a new review and improvements document (REVIEW_AND_IMPROVEMENTS.md) outlining 9 critical improvements and 12 enhancement opportunities for NPC behavior.
- Updated TECHNICAL_SPEC.md, IMPLEMENTATION_PLAN.md, QUICK_REFERENCE.md, and example_scenario.json with necessary changes regarding roomId tracking, sprite storage, wall collision setup, animation creation timing, and personal space behavior.
- Clarified async import patterns and depth update requirements in the implementation plan.
- Enhanced personal space behavior design to ensure NPCs back away slowly while maintaining eye contact with players.
- Documented all changes and improvements to ensure better integration with existing systems and reduce complexity in NPC behavior implementation.
- Changed trust_level variable to influence in helper-npc.ink and updated related logic.
- Adjusted dialogue and conditions to reflect influence instead of trust.
- Introduced new NPCs: Neye Eve and Gossip Girl, with timed messages for Gossip Girl.
- Updated itemsHeld in various NPCs to include phones with specific interactions.
- Introduced a data-driven global variable system to manage narrative state across NPC interactions.
- Added support for global variables in scenario JSON, allowing for easy extension and management.
- Implemented synchronization of global variables between Ink stories and the game state, ensuring real-time updates across conversations.
- Enhanced state persistence, allowing global variables to survive page reloads and be restored during conversations.
- Created comprehensive documentation and testing guides to facilitate usage and verification of the new system.
- Added a small delay before restarting conversations after NPC inventory interactions to ensure a smoother user experience.
- Updated the item synchronization logic in PersonChatConversation and PhoneChatConversation to set variables for items not in inventory, improving accuracy in item tracking.
- Enhanced the helper NPC dialogue to provide clearer options for item requests, enriching player engagement.
- Streamlined conversation flow for the Equipment Officer NPC, enhancing player engagement with clearer options for item inquiries.
- Added a new option to show specialist items, improving inventory management.
- Removed redundant trust level increments to simplify interaction logic.
- Updated exit conversation handling for a more polished user experience.
- Introduced a new method in ContainerMinigame to handle returning to conversations after NPC inventory interactions, enhancing user experience.
- Updated minigame exports to include the new return function for better integration.
- Enhanced PersonChatMinigame and PhoneChatMinigame to track current conversation context, improving narrative continuity.
- Added a new sprite asset for character representation in the game.
- Created a new documentation file detailing usage examples for the NPC item giving system, including immediate and container-based item transfers.
- Updated the ContainerMinigame to support additional NPC context, enhancing the user experience when interacting with NPC inventories.
- Implemented new NPC configurations in the scenario JSON to demonstrate item giving mechanics and container UI features.
- Added an Ink script for the Equipment Officer NPC, showcasing how to present items through the container UI and manage player interactions.
- Introduced new NPC inventory system allowing NPCs to hold and give items to players.
- Updated ContainerMinigame to support NPC mode, displaying NPC avatars and available items.
- Enhanced chat and conversation systems to sync NPC item states with Ink variables, improving narrative interactions.
- Added event listeners for item changes, ensuring dynamic updates during conversations.
- Implemented new methods in NPCGameBridge for item giving and inventory display, streamlining item interactions.
- Introduced a Set to keep track of characters that have undergone parallax animation, ensuring that the animation resets only for new speakers.
- Updated the logic to conditionally reset the parallax animation based on whether the speaker has been seen before, improving visual continuity during conversations.
- Updated CSS for the caption area to span the full width of the screen, enhancing visual consistency.
- Introduced a new inner container for caption content to maintain a maximum width, improving layout structure.
- Added parallax animation functionality in PersonChatPortraits for a more dynamic visual experience during conversations.
- Implemented automatic parallax animation reset when the speaker changes, ensuring smooth transitions between dialogues.
- Added support for optional background image paths in PersonChatMinigame, PersonChatPortraits, and PersonChatUI, allowing for more dynamic visual presentations during conversations.
- Updated NPCManager to handle background image paths in timed conversations, improving narrative context.
- Enhanced canvas rendering logic to accommodate background images, ensuring proper scaling and alignment with character sprites.
- Adjusted sprite positioning by shifting it 20% away from the direction the character is facing, improving the visual representation for both NPCs and players.
- Ensured consistent handling of sprite and image centering across the canvas for better overall aesthetics.
- Removed the outdated PersonChatMinigame implementation to streamline the codebase.
- Updated CSS for image handling in the chat minigame to use 'contain' for better aspect ratio maintenance.
- Improved canvas size management in PersonChatPortraits to ensure optimal rendering based on container dimensions, enhancing visual fidelity.
- Introduced a new documentation file detailing the Timed Conversations feature, which allows NPCs to automatically initiate dialogues after a specified delay.
- Included configuration examples and use cases to enhance narrative flow in scenarios.
- Updated NPCManager to support scheduling and triggering of timed conversations, improving interaction dynamics in the game.
- Added functionality to schedule timed conversations in NPCManager, allowing NPCs to automatically initiate dialogues after a specified delay.
- Updated PersonChatMinigame to handle multiple dialogue lines and speakers, improving the display logic for accumulated dialogue.
- Modified scenario JSON and Ink files to include timed conversation configurations for NPCs, enhancing narrative flow.
- Introduced NPCLazyLoader class to handle NPC loading on a per-room basis, optimizing memory usage and performance.
- Updated the create() function to utilize the new lazy loading mechanism for NPCs in the starting room.
- Refactored loadRoom function to support asynchronous NPC loading, ensuring NPCs are registered before room visuals are created.
- Adjusted PersonChatMinigame to load NPCs from the current room context, enhancing NPC management.
- Updated scenarios to reflect the new NPC structure, moving NPC definitions from scenario root to individual rooms.
- Consolidated async function updates for NPC loading in the `create()` function to streamline the process.
- Improved error handling during NPC loading for the starting room, ensuring room creation continues even if NPC loading fails.
- Updated documentation to reflect changes in the implementation checklist for better clarity on migration steps.
- Updated various planning documents to include additional details and clarity on the NPC migration process.
- Added new sections to CLIENT_SERVER_SEPARATION_PLAN.md, NPC_MIGRATION_OPTIONS.md, RAILS_ENGINE_MIGRATION_PLAN.md, and README.md to improve overall documentation and ensure comprehensive coverage of migration strategies.
- Ensured all documents reflect the latest architectural decisions and implementation plans for better guidance during the migration process.
- Create README.md outlining the entire migration plan, including executive summary, technical details, migration guide, API specification, and testing checklist.
- Introduce START_HERE.md as a quick start guide for implementation, detailing initial steps and phase breakdown.
- Develop VISUAL_GUIDE.md with diagrams and visual references for current vs. target architecture, NPC types, implementation phases, and memory usage comparisons.
refactor(js): Remove unused asset loading in preload function
feat(js): Implement optimal scale calculation for pixel-perfect rendering in person chat portraits