Unity Timeline Interaction System Integration (#17)

- Added InteractionTimelineAction component for timeline-driven interactions
- Implemented custom editor for timeline event mapping
- Updated interaction event flow to support timeline actions
- Enhanced character move target configuration
- Improved inspector UI for interactable components
- Added technical documentation for interaction system
- Refactored interaction action base classes for extensibility
- Fixed issues with character binding in timelines

Co-authored-by: Michal Pikulski <michal@foolhardyhorizons.com>
Co-authored-by: Michal Pikulski <michal.a.pikulski@gmail.com>
Reviewed-on: #17
This commit is contained in:
2025-10-07 10:57:11 +00:00
parent c46036dce6
commit 10992b43cc
48 changed files with 3062 additions and 254 deletions

277
docs/dialogue_readme.md Normal file
View File

@@ -0,0 +1,277 @@
# Apple Hills Dialogue System
This document provides an overview of the dialogue system used in Apple Hills, intended primarily for designers (Damian) working with the dialogue creation tools.
## Overview
The Apple Hills dialogue system is a node-based dialogue management system that allows for interactive conversations with NPCs. The system currently supports linear, condition-guarded dialogue paths that can respond to various game conditions such as puzzle completion, item pickups, and item combinations. While the architecture was designed to facilitate branching dialogue in future extensions, the current implementation follows a linear progression through nodes.
## Dialogue Structure
The dialogue system uses a graph-based structure with different types of nodes that control the flow of conversation. Each dialogue is represented as a graph containing multiple nodes connected through defined paths.
![Dialogue Graph Example](media/dialogue_graph_example.png)
### Core Components
1. **RuntimeDialogueGraph**: The container for all dialogue nodes that make up a conversation
- Defined in `Assets/Scripts/Dialogue/RuntimeDialogueGraph.cs`
- Contains the entry point node ID and a list of all dialogue nodes
- Holds the speaker name that appears in dialogue UI
2. **DialogueComponent**: Attached to game objects to manage dialogue state and progression
- Defined in `Assets/Scripts/Dialogue/DialogueComponent.cs`
- Manages the current state of dialogue (active node, line index)
- Responds to game events like puzzle completion, item pickup, etc.
- Controls dialogue advancement through player interaction
3. **SpeechBubble**: Handles the visual presentation of dialogue text
- Defined in `Assets/Scripts/Dialogue/SpeechBubble.cs`
- Manages the dialogue UI elements and text display
- Implements typewriter effects and visual prompts
## QuickStart Guide
Setting up a dialogue interaction in your scene is straightforward:
### 1. Component Setup
1. **Place the Dialogue Component**:
- Add the `DialogueComponent` to any game object that has an `Interactable` component
- The `Interactable` component handles player proximity and interaction triggers
- Make sure the interactable is properly configured with appropriate interaction radius
![Dialogue Component Inspector](media/dialogue_component_inspector.png)
2. **Add DialogueCanvas**:
- Add the "DialogueCanvas" prefab from the project assets as a child of your object
- Position the speech bubble appropriately above or near the interactable object
- The speech bubble should be clearly visible but not obstruct important scene elements
- You can adjust the scale and position to fit your specific character or object
![Speech Bubble Setup](media/speech_bubble_setup.png)
3. **Assign Dialogue Graph**:
- Create a `RuntimeDialogueGraph` scriptable object (Right Click > Create > Dialogue Graph)
- Set up your dialogue nodes in the graph (see Node Types for details)
- Assign the created graph to the `DialogueComponent` on your object
- Make sure to set the entry node ID in the dialogue graph
![Creating Dialogue Graph](media/create_dialogue_graph.png)
### 2. Testing Your Dialogue
1. Enter play mode and approach the interactable object
2. When the component has any lines to serve, the speech bubble should display the prompt ("...")
3. Interact with the object to advance through dialogue lines
4. Test any conditional nodes by completing their requirements
5. Verify that the dialogue progresses as expected
![Testing Dialogue Flow](media/dialogue_testing_flow.png)
### 3. Common Issues
- **No speech bubble appears**: Check that the DialogueCanvas is properly added as a child and is active
- **Dialogue doesn't advance**: Ensure the node connections (in/out) are properly set in the dialogue graph
- **Condition not triggering**: Verify that the condition IDs (puzzle step, item, etc.) match exactly with your game systems
## Node Types
The dialogue system supports several node types, each serving a specific purpose in the conversation flow:
### 1. Dialogue Node
Simple dialogue nodes display text to the player. They can contain multiple lines that are shown sequentially when the player interacts with the NPC.
**Key features:**
- Multiple dialogue lines displayed in sequence
- Optional looping through lines
- Automatic progression to the next node when all lines are exhausted
![Dialogue Node Example](media/dialogue_node_example.png)
**Implementation details:**
- Defined as `RuntimeDialogueNodeType.Dialogue` in `RuntimeDialogueGraph.cs`
- Uses `dialogueLines` list to store sequential lines of text
- The `loopThroughLines` boolean controls whether the dialogue returns to the first line after reaching the end
### 2. WaitOnPuzzleStep Node
This node pauses dialogue progression until a specific puzzle step has been completed by the player.
**Key features:**
- Automatically advances when the specified puzzle step is completed
- Displays dialogue while waiting for the condition to be met
- Visual prompt appears when the condition is met, indicating available dialogue
![WaitOnPuzzleStep Node Example](media/wait_on_puzzle_node.png)
**Implementation details:**
- Defined as `RuntimeDialogueNodeType.WaitOnPuzzleStep` in `RuntimeDialogueGraph.cs`
- Links to `PuzzleManager.OnStepCompleted` event through the `puzzleStepID` property
- The `DialogueComponent` listens for puzzle completion events through `OnAnyPuzzleStepCompleted` method
### 3. WaitOnPickup Node
This node waits until the player has picked up a specific item before advancing the dialogue.
**Key features:**
- Automatically advances when the player picks up the specified item
- Shows dialogue while waiting for the item pickup
- Visual prompt appears when the item is picked up, indicating available dialogue
![WaitOnPickup Node Example](media/wait_on_pickup_node.png)
**Implementation details:**
- Defined as `RuntimeDialogueNodeType.WaitOnPickup` in `RuntimeDialogueGraph.cs`
- Links to `ItemManager.OnItemPickedUp` event through the `pickupItemID` property
- The `DialogueComponent` listens for item pickup events through `OnAnyItemPickedUp` method
### 4. WaitOnSlot Node
This node requires the player to place a specific item in a designated slot before the dialogue can progress.
**Key features:**
- Supports different dialogue lines for different slot states:
- Default lines when no item is slotted
- Incorrect item lines when the wrong item is placed
- Forbidden item lines when a specifically disallowed item is placed
- Visual prompt appears when the correct item is slotted, indicating available dialogue
![WaitOnSlot Node Example](media/wait_on_slot_node.png)
**Implementation details:**
- Defined as `RuntimeDialogueNodeType.WaitOnSlot` in `RuntimeDialogueGraph.cs`
- Uses multiple events from `ItemManager` including:
- `OnCorrectItemSlotted` - Triggered when the matching `slotItemID` is placed
- `OnIncorrectItemSlotted` - For displaying incorrect item dialogue
- `OnForbiddenItemSlotted` - For displaying forbidden item dialogue
- `OnItemSlotCleared` - For resetting to default dialogue
### 5. WaitOnCombination Node
This node waits for the player to create a specific item through the combination system.
**Key features:**
- Automatically advances when the player creates the specified item through combination
- Shows dialogue while waiting for the item combination
- Visual prompt appears when the item is created, indicating available dialogue
![WaitOnCombination Node Example](media/wait_on_combination_node.png)
**Implementation details:**
- Defined as `RuntimeDialogueNodeType.WaitOnCombination` in `RuntimeDialogueGraph.cs`
- Links to `ItemManager.OnItemsCombined` event through the `combinationResultItemID` property
- The `DialogueComponent` listens for item combination events through `OnAnyItemsCombined` method
### 6. End Node
Terminates the dialogue sequence.
**Key features:**
- Marks the dialogue as completed
- No further interaction available until the dialogue is restarted
![End Node Example](media/end_node.png)
**Implementation details:**
- Defined as `RuntimeDialogueNodeType.End` in `RuntimeDialogueGraph.cs`
- When reached, sets the `IsCompleted` flag on the `DialogueComponent`
- No next node connection is required for this node type
## Dialogue Editor
The dialogue editor is a custom Unity tool that allows for visual creation and editing of dialogue graphs.
![Dialogue Editor Interface](media/dialogue_editor_interface.png)
### Key Editor Features
- **Visual Node Editing**: Add and connect nodes in a visual graph
- **Node Type Selection**: Choose from the six supported node types
- **Dialogue Text Entry**: Add multiple lines of dialogue for each node
- **Condition Setup**: Specify condition IDs for conditional nodes
- **Node Connections**: Create the flow between dialogue nodes
### Editor Workflow
1. **Create New Graph**: Right-click in Project view and select Create > Dialogue Graph
2. **Open Editor**: Double-click the created asset to open the dialogue editor
3. **Add Nodes**: Right-click in the editor and select Add Node > [Node Type]
4. **Configure Nodes**: Enter dialogue text and set conditions as needed
5. **Connect Nodes**: Drag from output ports to input ports to create connections
6. **Set Entry Node**: Mark one node as the entry point for the dialogue
7. **Save**: Save your dialogue graph when finished
## Designer Tips
1. **Node Organization**
- Start every dialogue graph with a standard Dialogue node as the entry point
- End every dialogue path with an End node to properly terminate the conversation
- Use conditional nodes strategically to create gameplay-driven dialogue experiences
2. **Dialogue Writing**
- Keep individual dialogue lines concise for better readability
- Consider using the looping option for nodes when you want to repeat information
- For WaitOnSlot nodes, write unique dialogue for incorrect/forbidden items to provide clear feedback
3. **Flow Control**
- Ensure all nodes (except End nodes) have a valid next node specified
- Test dialogue paths to verify all conditions can be met during gameplay
- Consider using multiple dialogue lines within a single node rather than creating separate nodes for sequential lines
4. **Best Practices**
- Name your nodes descriptively in the editor for easier management
- Group related dialogue sequences into separate dialogue graphs
- Use the speaker name field to clearly identify who is speaking
## Technical Details
### Public Events and APIs
The dialogue system exposes several events that can be used by other systems:
#### DialogueComponent
- **Events**:
- `OnDialogueChanged`: Triggered when the dialogue text changes
- **Properties**:
- `IsActive`: Indicates whether the dialogue is currently active
- `IsCompleted`: Indicates whether the dialogue has reached an End node
- `CurrentSpeakerName`: Returns the name of the current speaker
- **Public Methods**:
- `StartDialogue()`: Initiates the dialogue from the beginning
- `GetCurrentDialogueLine()`: Retrieves the current dialogue line text
- `HasAnyLines()`: Checks if the dialogue component has any lines available
- `SetDialogueGraph(RuntimeDialogueGraph)`: Sets the dialogue graph for the component
#### SpeechBubble
- **Public Methods**:
- `Show()`: Makes the speech bubble visible
- `Hide()`: Hides the speech bubble
- `Toggle()`: Toggles the visibility of the speech bubble
- `SetText(string)`: Sets the text displayed in the speech bubble
- `DisplayDialogueLine(string, bool)`: Displays a dialogue line and handles prompt visibility
- `UpdatePromptVisibility(bool)`: Updates the speech bubble to show a prompt or hide based on dialogue availability
- `SetDisplayMode(TextDisplayMode)`: Changes how text is displayed (instant or typewriter)
- `SkipTypewriter()`: Immediately displays the full text, skipping the typewriter effect
- `SetTypewriterSpeed(float)`: Sets the speed of the typewriter effect
### Integration with Other Systems
The dialogue system integrates with several other game systems:
1. **Puzzle System**: Monitors puzzle completion events to advance WaitOnPuzzleStep nodes
2. **Item System**: Tracks item pickups, combinations, and slot interactions to advance respective node types
3. **Interaction System**: Responds to player interaction with the NPC to progress through dialogue lines
### Technical Workflow
1. Create a RuntimeDialogueGraph asset in the Unity editor
2. Add nodes and connections using the dialogue editor
3. Assign the graph to a DialogueComponent on an NPC GameObject
4. Ensure a SpeechBubble component is available (as a child object or referenced)
5. Set up any necessary puzzle steps, items, or slots that the dialogue will reference

View File

@@ -0,0 +1,275 @@
# Apple Hills Interaction System
This document provides a comprehensive overview of the interaction system in Apple Hills, detailing how interactions are structured, configured, and extended with custom actions.
## Overview
The Apple Hills interaction system allows players to interact with objects in the game world. It supports character movement to interaction points, timed and conditional interactions, and complex behaviors through a component-based architecture. The system is particularly powerful when combined with the Timeline feature for creating cinematic sequences during interactions.
## Core Components
The interaction system consists of several key components that work together:
### Interactable
The `Interactable` component is the foundation of the interaction system. It:
- Handles player input (tapping/clicking)
- Manages which character(s) should interact (Trafalgar, Pulver, or both)
- Coordinates character movement to interaction points
- Dispatches events during the interaction lifecycle
- Manages one-time interactions and cooldowns
![Interactable Inspector](media/interactable_inspector.png)
### CharacterMoveToTarget
The `CharacterMoveToTarget` component defines positions where characters should move when interacting:
- Can be configured for specific characters (Trafalgar, Pulver, or both)
- Supports position offsets for fine-tuning
- Provides visual gizmos in the editor for easy positioning
- Multiple targets can be set up for complex interactions
![Character Move Target Inspector](media/character_move_target_inspector.png)
### Interaction Actions
Actions are components that respond to interaction events and execute custom behavior:
- Derive from the abstract `InteractionActionBase` class
- Can be attached to interactable objects
- Multiple actions can be added to a single interactable
- Actions can optionally block the interaction flow until completion
The inspector for all interaction action components shows the key parameters from InteractionActionBase, with custom configuration options for specific action types:
![InteractionTimelineAction Inspector](media/interaction_timeline_action_inspector.png)
### Interaction Requirements
Requirements are components that determine whether an interaction can occur:
- Derive from the abstract `InteractionRequirementBase` class
- Can prevent interactions based on custom conditions
- Multiple requirements can be added to a single interactable
- Used for creating conditional interactions (e.g., requiring an item)
## Interaction Event Flow
Interactions follow a defined event flow:
1. **InteractionStarted**: Triggered when the player initiates an interaction
2. **PlayerArrived**: Triggered when the player character reaches the interaction point
3. **InteractingCharacterArrived**: Triggered when the interacting character (often Pulver) reaches the interaction point
4. **InteractionComplete**: Triggered when the interaction is completed
5. **InteractionInterrupted**: Triggered if the interaction is interrupted before completion
## InteractionActionBase
The `InteractionActionBase` is the abstract base class for all interaction actions. It provides the framework for creating custom behaviors that respond to interaction events.
### Key Features
- **Event Filtering**: Actions can choose which interaction events to respond to
- **Flow Control**: Actions can optionally pause the interaction flow until completion
- **Asynchronous Execution**: Actions use `async/await` pattern for time-consuming operations
- **Character References**: Actions receive references to both player and follower characters
### Implementation
```csharp
public abstract class InteractionActionBase : MonoBehaviour
{
// Which events this action should respond to
public List<InteractionEventType> respondToEvents;
// Whether to pause the interaction flow during execution
public bool pauseInteractionFlow;
// The main execution method that must be implemented by derived classes
protected abstract Task<bool> ExecuteAsync(
InteractionEventType eventType,
PlayerTouchController player,
FollowerController follower);
// Optional method for adding execution conditions
protected virtual bool ShouldExecute(
InteractionEventType eventType,
PlayerTouchController player,
FollowerController follower)
{
return true;
}
}
```
## InteractionTimelineAction
The `InteractionTimelineAction` is a powerful action that plays Unity Timeline sequences during interactions. It enables cinematic sequences, character animations, camera movements, and more.
### Key Features
- **Multiple Timeline Support**: Can play different timelines for different interaction events
- **Timeline Sequences**: Can play multiple timelines in sequence for a single event
- **Character Binding**: Automatically binds player and follower characters to timeline tracks
- **Flow Control**: Waits for timeline completion before continuing interaction flow
- **Timeout Safety**: Includes a configurable timeout to prevent interactions from getting stuck
- **Looping Options**: Supports looping all timelines or just the last timeline in a sequence
### Timeline Event Mapping
Each mapping connects an interaction event to one or more timeline assets:
```csharp
public class TimelineEventMapping
{
// The event that triggers this timeline
public InteractionEventType eventType;
// The timeline assets to play (in sequence)
public PlayableAsset[] timelines;
// Character binding options
public bool bindPlayerCharacter;
public bool bindPulverCharacter;
public string playerTrackName = "Player";
public string pulverTrackName = "Pulver";
// Playback options
public float timeoutSeconds = 30f;
public bool loopLast = false;
public bool loopAll = false;
}
```
### Custom Editor
The `InteractionTimelineAction` includes a custom editor that makes it easy to configure:
- Quick buttons to add mappings for common events
- Character binding options
- Timeline sequence configuration
- Validation warnings for misconfigured timelines
![Timeline Mapping Editor](media/timeline_mapping_editor.png)
### Implementation Pattern
For a cinematic interaction with timelines:
1. Add an `Interactable` component to your object
2. Add an `InteractionTimelineAction` component to the same object
3. Set up character move targets if needed
4. Create timeline assets for each interaction phase
5. Configure the timeline mappings in the inspector
6. Test the interaction in play mode
### Timeline Configuration
When setting up a timeline for interaction, you'll need to create a Timeline asset and configure it in Unity's Timeline editor:
![Timeline Editor](media/timeline_editor.png)
## Working with the Interactable Editor
The `Interactable` component includes a custom editor that enhances the workflow:
### Character Move Target Creation
The editor provides buttons to easily create character move targets:
- "Add Trafalgar Target" - Creates a move target for the player character
- "Add Pulver Target" - Creates a move target for the follower character
- "Add Both Characters Target" - Creates a move target for both characters
![Interactable Custom Editor](media/interactable_inspector.png)
### Target Visualization
The editor displays the number of targets for each character type and warns about potential conflicts:
```
Trafalgar Targets: 1, Pulver Targets: 1, Both Targets: 0
```
If multiple conflicting targets are detected, a warning is displayed to help prevent unexpected behavior.
## Best Practices
### Target Positioning
- Place character targets with appropriate spacing to prevent characters from overlapping
- Consider the character's facing direction (targets automatically make characters face the interactable)
- Use the position offset for fine-tuning without moving the actual target GameObject
![Target Positioning In Scene](media/target_positioning_scene.png)
### Timeline Design
- Keep timelines modular and focused on specific actions
- Use signals to trigger game events from timelines
- Consider using director notification tracks for advanced timeline integration
- Test timelines with actual characters to ensure animations blend correctly
### Action Combinations
- Combine multiple actions for complex behaviors (e.g., dialogue + timeline)
- Order actions in the Inspector to control execution priority
- Use the `pauseInteractionFlow` option strategically to control sequence flow
## Technical Reference
### InteractionEventType
```csharp
public enum InteractionEventType
{
InteractionStarted, // When interaction is first triggered
PlayerArrived, // When player arrives at interaction point
InteractingCharacterArrived, // When interacting character arrives
InteractionComplete, // When interaction is successfully completed
InteractionInterrupted // When interaction is interrupted
}
```
### CharacterToInteract
```csharp
public enum CharacterToInteract
{
None, // No character interactions
Trafalgar, // Player character only
Pulver, // Follower character only
Both // Both characters
}
```
## Troubleshooting
### Common Issues
- **Characters not moving to targets**: Ensure targets have the correct CharacterToInteract type set
- **Timeline not playing**: Check that the PlayableDirector has a reference to the timeline asset
- **Characters not appearing in timeline**: Verify the track names match the binding configuration
- **Interaction getting stuck**: Make sure timelines have a reasonable timeout value set
- **Multiple timelines playing simultaneously**: Check that the event mappings are correctly configured
## Setup Example
Here's how a typical interaction setup might look in the Inspector:
1. Interactable component with appropriate settings
2. Character move targets positioned in the scene
3. InteractionTimelineAction component configured with timeline mappings
4. PlayableDirector component referencing timeline assets
## Advanced Topics
### Timeline Integration with Dialogue
Timeline actions can be synchronized with dialogue using:
- Animation tracks to trigger dialogue displays
- Signal tracks to advance dialogue
- Custom markers to synchronize dialogue with character animations
### Interaction Sequences
Complex interaction sequences can be created by:
- Using multiple interactables in sequence
- Enabling/disabling interactables based on game state
- Using timelines to guide the player through sequential interactions

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 288 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

BIN
docs/media/end_node.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB