> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lokutor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Game characters

> What makes a voice character feel alive in Unity and Godot: a short persona, facts of the moment, actions with consequences, written lines, and the layers of animation: clips, springs, moods, visemes

A voice that answers is half of a character. The other half is that it knows what is happening, can do something about it, and moves like it means it. This page is the recipe, in the order we build one.

## Personality

The **persona** is the system prompt of the conversation. It is read on every turn, so every sentence in it should earn its place. Four parts are enough:

```
You are Mira, who keeps the only inn on the pass. Dry, tired, kind underneath.        who
The player is a courier who arrived soaked, after dark. You have one room left.       situation
Answer what they said in one or two short sentences, never more than twenty words.    how to talk
Never explain the game, never offer a list of options, never break character.         what not to do
```

* **Give it a want.** A character that wants something ("you want the player to leave before your brother comes back") drives a conversation; a helpful one waits to be asked.
* **Say how it opens.** The character speaks first. Without an opening to say, it may talk about its instructions instead: "You speak first: one bored line, such as 'Next! Another jester.'" Give it the actions and the rest of its persona when it has greeted the player, not before: with an action it must call before every answer already in front of it, it read its instructions out in 7 openings of 8, and "do not call it for the opening" did not help.
* **Say how long.** Spoken sentences feel longer than written ones, and short answers arrive sooner.
* **Put the obstacle in the game, not in the prompt.** "Do not give the key unless they pay" is a request; an action that checks the gold is a rule.
* **Write for the ear.** Plain words only: no stage directions, no emoji. For a laugh or a sigh in the voice there are [expression tags](https://docs.lokutor.com/api-reference/expression-tags.md), which take a second or more each: use them rarely. With tags in the persona, give the values of an action names that cannot pass for one (`stone_face`, not `bored`): a bracket that is not a tag is read aloud.
* **Pick the voice with the persona.** `F1`-`F5` and `M1`-`M5` are ten people; `pitch` makes a goblin or an ogre out of them. Try the same line in several.
* **Languages**: with `auto` the character follows the player's. It speaks thirteen and understands nine ([which](https://docs.lokutor.com/voices-languages-models.md#which-languages-are-understood)).

## Facts of the moment

What changes goes in **context**, not in the persona: short facts with a name, which you overwrite as the game goes.

```csharp Unity theme={null}
mira.SetContext("Gold the player has", "12");
mira.SetContext("The weather", "A storm. The road is closed until morning.");
mira.SetContext("What the player is holding", "Your brother's knife.");
mira.SetContext("The weather", null);          // no longer true
```

```gdscript Godot theme={null}
mira.set_context("Gold the player has", 12)
mira.set_context("The weather", "A storm. The road is closed until morning.")
mira.set_context("What the player is holding", "Your brother's knife.")
mira.set_context("The weather", null)          # no longer true
```

Changes are sent together, and they survive a reconnection. Keep the facts few and rounded ("about twenty seconds left", not a number every frame): each change is a new prompt. A number that is always there gets said in every answer: send it only when it matters ("almost over: hurry them once"). The character uses them in its next reply; a new fact does not make it speak.

## Actions

Actions are how a conversation has consequences ([Unity](https://docs.lokutor.com/sdks/unity/actions.md), [Godot](https://docs.lokutor.com/sdks/godot/actions.md)). Three kinds cover most characters:

| | Example | What it returns |
| :- | :- | :- |
| **Change the world** | `give_item`, `open_gate`, `join_party` | What changed, or why it did not: *The player has only 8 gold: not enough.* |
| **Show a feeling** | `react` with one of five feelings and a number | *Done.*, or what it leads to: *You cannot hold it any longer: laugh out loud.* |
| **End the scene** | `call_the_guards`, `walk_away` | *The guards are coming. Say one word.* |

The sentence an action returns is the strongest lever you have: the character speaks right after reading it. Use it to steer ("You are now at 80 of 100"), and to say no.

Ask for `react` on every answer, *before speaking*, and the body moves while the voice is still being made. That hides the latency, and the number is your game's score.

## Written lines

Not everything should be improvised. A [written line](https://docs.lokutor.com/sdks/godot/speech.md#written-lines) costs once, starts at once, works offline when shipped, and says exactly what you want: tutorial hints, barks, the first and last line of a scene. The same character can have both. Use a conversation where the player's own words matter, and written lines everywhere else.

```csharp Unity theme={null}
async Task ThrowOut()
{
    mira.StopConversation();
    await miraVoice.Say("That is enough. Out.");
    door.Open();
}
```

```gdscript Godot theme={null}
func throw_out() -> void:
    mira.stop_conversation()
    await mira_voice.say("That is enough. Out.")
    $Door.open()
```

## Layers

A character that is alive is several simple things running at once, each on its own part of the body. From the bottom up:

| Layer | What it is | Driven by |
| :- | :- | :- |
| **Clips** | Idle, listen, talk, react: body animation made by hand | The agent's state and `react` |
| **Look** | The head (and eyes) turn to whom it is talking to | Where the player or the speaker is |
| **Springs** | Belly, hat, ears, cloth: bones that lag and wobble | Whatever the layers below did |
| **Mood** | Brows, eyes, the mouth at rest: expression blend shapes | `react`, the story |
| **Blinks and glances** | Every few seconds, never in time with each other | A random clock |
| **Visemes** | The mouth while speaking | [LokutorLipSync](https://docs.lokutor.com/sdks/godot/lip-sync.md) |
| **Accents** | Small nods and a little squash on loud syllables | `mouth_open` |

Three rules keep them out of each other's way:

1. **One writer per bone and per blend shape.** Clips move bones and never touch the face; moods own the expression shapes; LokutorLipSync owns the viseme shapes. If a body clip has face tracks, delete them.
2. **Order.** Clip, then look, then springs, so springs react to everything. In Godot: an `AnimationPlayer`, then two `SkeletonModifier3D` under the skeleton, in that order. In Unity: the Animator, then `LateUpdate`, where LokutorLipSync already works.
3. **Give way while speaking.** A smile and an `aa` on the same mouth add up to a shape nobody drew. Fade the *mouth* shapes of the mood to about 30% while the character speaks and leave brows and eyes alone: the smile still shows, and the lips still close on *p*, *b* and *m*.

### From conversation to body

```csharp Unity theme={null}
using Lokutor;
using UnityEngine;

public class Body : MonoBehaviour
{
    public LokutorAgent agent;
    public Animator animator;

    void Awake()
    {
        agent.onStateChanged.AddListener(OnState);
        agent.onCharacterInterrupted.AddListener(heard => animator.SetTrigger("Startled"));
    }

    void OnState(AgentState state)
    {
        animator.SetBool("Listening", state == AgentState.PlayerTalking);      // lean in, the moment they talk
        animator.SetBool("Thinking", state == AgentState.Thinking);            // look up, scratch the beard
        animator.SetBool("Talking", state == AgentState.Speaking);
    }
}
```

```gdscript Godot theme={null}
extends Node

@export var agent: LokutorAgent
@export var anim: AnimationPlayer

const CLIPS := {
    LokutorAgent.State.READY: "idle",
    LokutorAgent.State.PLAYER_TALKING: "listen",      # lean in, the moment they talk
    LokutorAgent.State.THINKING: "think",             # look up, scratch the beard
    LokutorAgent.State.SPEAKING: "talk",
}

func _ready() -> void:
    agent.state_changed.connect(_on_state)
    agent.character_interrupted.connect(func(_heard): anim.play("startled", 0.1))

func _on_state(state: LokutorAgent.State) -> void:
    if CLIPS.has(state):
        anim.play(CLIPS[state], 0.3)
```

Blend slowly into calm clips (0.3 s or more) and fast into reactions (0.1 s). Two or three talking clips picked at random are worth more than one perfect one.

### Moods that move out of the way

A mood is a set of weights. Ease towards it, with the mouth held back while the character speaks:

```csharp Unity theme={null}
using System.Collections.Generic;
using Lokutor;
using UnityEngine;

public class Face : MonoBehaviour
{
    public LokutorAgent agent;
    public SkinnedMeshRenderer face;

    static readonly Dictionary<string, Dictionary<string, float>> Moods = new Dictionary<string, Dictionary<string, float>>
    {
        ["neutral"] = new Dictionary<string, float>(),
        ["happy"] = new Dictionary<string, float> { ["smile"] = 0.9f, ["brow_up"] = 0.35f },
        ["angry"] = new Dictionary<string, float> { ["grit"] = 0.75f, ["brow_angry"] = 1f },
    };
    static readonly HashSet<string> Mouths = new HashSet<string> { "smile", "grit" };

    readonly Dictionary<string, float> now = new Dictionary<string, float>();
    string mood = "neutral";
    float speaking;

    public void SetMood(string newMood) => mood = newMood;

    void Update()
    {
        speaking = Mathf.MoveTowards(speaking, agent.IsSpeaking ? 1f : 0f, Time.deltaTime * 9f);
        foreach (string shape in new[] { "smile", "grit", "brow_up", "brow_angry" })
        {
            Moods[mood].TryGetValue(shape, out float target);
            if (Mouths.Contains(shape)) target *= Mathf.Lerp(1f, 0.3f, speaking);
            now.TryGetValue(shape, out float value);
            now[shape] = value = Mathf.Lerp(value, target, 1f - Mathf.Exp(-Time.deltaTime * 12f));
            int index = face.sharedMesh.GetBlendShapeIndex(shape);
            if (index >= 0) face.SetBlendShapeWeight(index, value * 100f);
        }
    }
}
```

```gdscript Godot theme={null}
extends Node

@export var agent: LokutorAgent
@export var face: MeshInstance3D

const MOODS := {
    "neutral": {},
    "happy": {"smile": 0.9, "brow_up": 0.35},
    "angry": {"grit": 0.75, "brow_angry": 1.0},
}
const MOUTHS := ["smile", "grit"]

var mood := "neutral"
var _speaking := 0.0
var _now := {}

func _process(delta: float) -> void:
    _speaking = move_toward(_speaking, 1.0 if agent.is_speaking else 0.0, delta * 9.0)
    for shape in ["smile", "grit", "brow_up", "brow_angry"]:
        var target: float = MOODS[mood].get(shape, 0.0)
        if shape in MOUTHS:
            target *= lerpf(1.0, 0.3, _speaking)
        _now[shape] = lerpf(_now.get(shape, 0.0), target, 1.0 - exp(-delta * 12.0))
        var index := face.find_blend_shape_by_name(shape)
        if index >= 0:
            face.set_blend_shape_value(index, _now[shape])
```

For a cartoon, replace the easing with a spring that overshoots a little: expressions pop.

### Blinks, glances, nods

* **Blinks** last about 0.17 s, every 2 to 5 seconds, now and then two in a row. Blink on a change of mood or of look: people do.
* **Eyes jump**, they do not slide. A glance away every couple of seconds while listening, less while speaking.
* **Nods** follow the voice: feed a smoothed `mouth_open` (`MouthOpen` in Unity) into a few degrees of head pitch, plus slow sines on the other two axes while speaking. Nobody talks with a still head.
* **Springs** go last, as bones that chase their animated place with a stiffness and a damping. Clips then do not need overlapping action drawn by hand, and reactions blended halfway still look right.

## The player's character

When the player is on screen, their mouth has no visemes: it is their own voice. Drive the same LokutorLipSync with the level of the microphone:

```csharp Unity theme={null}
void Update() => playerLips.Advance(0f, agent.Mic.Level * 3f, agent.Mic.Level > 0.03f, Time.deltaTime);
```

```gdscript Godot theme={null}
func _process(delta: float) -> void:
    var level: float = agent.microphone.level if agent.microphone else 0.0
    player_lips.advance(0.0, clampf(level * 3.0, 0.0, 1.0), level > 0.03, delta)
```

## Characters that talk to each other

Two agents can hear each other. Turn both microphones off (`MicMode.Off` / `MicMode.OFF`) before they start, and feed each one what the other plays: `VoicePlayed` into `FeedMicrophone`, `voice_played` into `feed_microphone`. Those events carry only the voice, so send silence the rest of the time, in real time: the server tells that a turn is over by the silence after it.

Each agent is a [session](https://docs.lokutor.com/pricing.md#limits) and is billed on its own, and two characters left alone never stop. For a scripted exchange, written lines are cheaper and always land.

## Checklist

* It notices the player before they speak (looks, turns, stops what it was doing).
* Something moves within a frame of every state change.
* It does not answer before it has been seen to listen.
* Every action that can fail says why.
* Subtitles for both (`player_said`, `character_said`), and a way to talk without a microphone.
* Interrupting it feels good: it stops, and its face shows it.
* It is closed when the player leaves.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.