Murder Mansion
A social deduction game in a dark mansion on a stormy night. Players queue in the lobby. When enough have joined, everyone in the queue is dealt into the house with a secret role:
- Murderers carry a knife and must kill every innocent.
- One Detective carries a revolver and can shoot anyone. Shooting an innocent kills the Detective too.
- Bystanders must survive. If the Detective falls, any bystander can pick up the dropped revolver.
Dead players and players waiting for the next round watch a live map of the house on the lobby wall.
Get it from the StageTime-Worlds-Examples repository: copy the Worlds/MurderMansion folder into a Unity
project that has the StageTime World SDK, and open its scene.
| Piece | Built with |
|---|---|
| Queue | An ST Queue with one entry per player; a lectern button joins or leaves it |
| Rounds and roles | One script with synced arrays; only its owner starts rounds, deals roles and applies kills |
| Knives | ST Pickup (drawn with F on desktop through PickUp) with a trigger blade: OnPlayerTriggerEnter touches the victim's body or head |
| Desktop stabs | STPhysics.Raycast from the head, which reports players (Aiming at players) |
| Revolver | ST Pickup + ST Projectile Launcher with Hit Players; OnProjectileHit names the victim |
| Spectator map | A wall canvas with one dot per round slot, placed from StageTimePlayer.GetPosition() |
| Private messages | A world-space panel that follows the local player's head |
| Storm | Lightning and thunder worked out from the room clock, so every device sees the same flash |
The game
MurderGame holds the whole round in synced fields: the phase, the slots (player IDs, roles and states), the gun
bearer and a small event code that devices announce. Everything else is derived from it on each device.
Its owner is the only device that changes it. The owner moves the phases forward, shuffles the queue into roles and applies kills. Weapons report a kill to the game, and the owner checks it: the round must match, a knife must come from a living murderer and a shot from the player holding the revolver, and the victim must still be alive. This rule keeps the game fair when two devices see the same stab, or when a report arrives after the round has ended.
using StageTime.SDK;
using UnityEngine;
/// <summary>
/// Murder Mansion rules. Players queue in the lobby (the ST Queue on this GameObject); when enough are waiting a
/// countdown starts, then up to 16 of them are dealt roles and sent into the house: one Detective with the revolver,
/// one to three Murderers with knives, and Bystanders. Murderers win when every innocent is dead; innocents win when
/// every murderer is dead or the clock runs out. A Detective who shoots an innocent dies too and drops the revolver,
/// which any living innocent can pick up.
///
/// Only this object's owner (the room's master at first) changes the round; weapons report kills here and the owner
/// applies them, so a kill never counts twice. Everyone else reacts in <see cref="MurderPresenter"/>.
/// </summary>
public class MurderGame : StageTimeBehaviour
{
public const int Waiting = 0, Countdown = 1, Playing = 2, Ended = 3;
public const int None = 0, Bystander = 1, Murderer = 2, Detective = 3;
public const int Alive = 0, Knifed = 1, Shot = 2, Gone = 3, Punished = 4;
public const int NoWinner = 0, MurderersWin = 1, InnocentsWin = 2;
public const int EventGunDropped = 1, EventWrongTarget = 2;
public const int MaxPlayers = 16;
[Tooltip("Players needed in the queue before a round counts down.")]
public int minPlayers = 3;
public float countdownSeconds = 15f;
public float roundSeconds = 300f;
[Tooltip("Seconds the result shows before players return to the lobby.")]
public float endSeconds = 8f;
[Tooltip("How many knives exist; also the most murderers a round can have.")]
public int knifeCount = 3;
[Tooltip("A Detective who shoots an innocent dies too.")]
public bool detectivePenalty = true;
[Synced] private int phase;
[Synced] private int round;
[Synced] private double phaseEnd;
[Synced] private int spawnOffset;
[Synced] private int gunBearer = -1;
[Synced] private int winner;
[Synced] private int eventCode;
[Synced] private int eventSeq;
[Synced] private int[] ids = new int[MaxPlayers]; // player id + 1; 0 = empty slot
[Synced] private int[] roles = new int[MaxPlayers];
[Synced] private int[] states = new int[MaxPlayers];
private STQueue queue;
private float nextCheck;
private int version = 1;
/// <summary>
/// Changes whenever the state may have changed on this device. The presenter polls it: calling the presenter from
/// here would be re-entrant, as the presenter calls back into this script.
/// </summary>
public int Version() => version;
public int Phase() => phase;
public int Round() => round;
public int Winner() => winner;
public int EventCode() => eventCode;
public int EventSeq() => eventSeq;
public int SpawnOffset() => spawnOffset;
public int GunBearer() => gunBearer;
public bool GunDropped() => phase == Playing && gunBearer < 0;
public double SecondsLeft()
{
double left = phaseEnd - Networking.GetServerTimeInSeconds();
return phase != Waiting && left > 0.0 ? left : 0.0;
}
private void Start()
{
queue = GetComponent<STQueue>();
}
public override void OnDeserialization() => version++;
// ---- queries (any device) ------------------------------------------------------------------------------------
/// <summary>The round slot of a player, or -1 when they are not playing this round.</summary>
public int SlotOf(int playerId)
{
if (phase == Waiting || phase == Countdown) return -1;
for (int i = 0; i < MaxPlayers; i++)
if (ids[i] == playerId + 1) return i;
return -1;
}
public int PlayerIdAt(int slot) => ids[slot] - 1;
public int RoleAt(int slot) => roles[slot];
public int StateAt(int slot) => states[slot];
public int RoleOf(int playerId) { int s = SlotOf(playerId); return s < 0 ? None : roles[s]; }
public bool IsAlive(int playerId) { int s = SlotOf(playerId); return s >= 0 && states[s] == Alive && phase == Playing; }
/// <summary>The player id holding knife <paramref name="index"/> this round (the index-th murderer), or -1.</summary>
public int KnifeBearer(int index)
{
if (phase != Playing) return -1;
int found = 0;
for (int i = 0; i < MaxPlayers; i++)
{
if (ids[i] == 0 || roles[i] != Murderer) continue;
if (found++ == index) return states[i] == Alive ? ids[i] - 1 : -1;
}
return -1;
}
public int CountAlive(bool murderers)
{
int count = 0;
for (int i = 0; i < MaxPlayers; i++)
if (ids[i] != 0 && states[i] == Alive && (roles[i] == Murderer) == murderers) count++;
return count;
}
// ---- owner: the round clock ------------------------------------------------------------------------------------
private void Update()
{
if (!Networking.IsOwner(gameObject) || Time.time < nextCheck) return;
nextCheck = Time.time + 0.25f;
double now = Networking.GetServerTimeInSeconds();
int queued = queue.count;
if (phase == Waiting)
{
if (queued >= minPlayers) SetPhase(Countdown, now + countdownSeconds);
}
else if (phase == Countdown)
{
if (queued < minPlayers) SetPhase(Waiting, 0.0);
else if (now >= phaseEnd) StartRound(now);
}
else if (phase == Playing)
{
for (int i = 0; i < MaxPlayers; i++)
if (ids[i] != 0 && states[i] == Alive && StageTimePlayer.GetPlayerById(ids[i] - 1) == null) Kill(i, Gone);
if (!CheckWin() && now >= phaseEnd) EndRound(InnocentsWin);
}
else if (now >= phaseEnd)
{
SetPhase(Waiting, 0.0);
}
}
private void SetPhase(int next, double end)
{
phase = next;
phaseEnd = end;
version++;
}
private void StartRound(double now)
{
for (int i = 0; i < MaxPlayers; i++) { ids[i] = 0; roles[i] = None; states[i] = Alive; }
int count = 0;
for (int i = 0; i < queue.count && count < MaxPlayers; i++)
{
int id = queue.GetPlayerId(i);
if (StageTimePlayer.GetPlayerById(id) == null || Contains(id, count)) continue;
ids[count++] = id + 1;
}
if (count < minPlayers) { SetPhase(Waiting, 0.0); return; }
for (int i = count - 1; i > 0; i--) // shuffle, so roles and spawns don't follow queue order
{
int j = Random.Range(0, i + 1);
int swap = ids[i]; ids[i] = ids[j]; ids[j] = swap;
}
int murderers = Mathf.Clamp(count <= 5 ? 1 : count <= 10 ? 2 : 3, 1, Mathf.Max(1, knifeCount));
gunBearer = -1;
for (int i = 0; i < count; i++)
{
roles[i] = i < murderers ? Murderer : i == murderers ? Detective : Bystander;
if (roles[i] == Detective) gunBearer = ids[i] - 1;
}
for (int i = count - 1; i > 0; i--) // shuffle again so the slot doesn't give the role away
{
int j = Random.Range(0, i + 1);
int swapId = ids[i]; ids[i] = ids[j]; ids[j] = swapId;
int swapRole = roles[i]; roles[i] = roles[j]; roles[j] = swapRole;
}
round++;
winner = NoWinner;
spawnOffset = Random.Range(0, 64);
SetPhase(Playing, now + roundSeconds);
}
private bool Contains(int id, int count)
{
for (int i = 0; i < count; i++) if (ids[i] == id + 1) return true;
return false;
}
private bool CheckWin()
{
if (CountAlive(true) == 0) { EndRound(InnocentsWin); return true; }
if (CountAlive(false) == 0) { EndRound(MurderersWin); return true; }
return false;
}
private void EndRound(int result)
{
winner = result;
gunBearer = -1;
SetPhase(Ended, Networking.GetServerTimeInSeconds() + endSeconds);
}
// ---- reports (applied on the owner's device only) ---------------------------------------------------------------
/// <summary>A murderer's knife touched <paramref name="victimId"/> during <paramref name="reportRound"/>.</summary>
public void ReportKnife(int killerId, int victimId, int reportRound)
{
if (!Networking.IsOwner(gameObject) || phase != Playing || reportRound != round) return;
int killer = SlotOf(killerId), victim = SlotOf(victimId);
if (killer < 0 || victim < 0 || states[killer] != Alive || states[victim] != Alive) return;
if (roles[killer] != Murderer || roles[victim] == Murderer) return;
Kill(victim, Knifed);
CheckWin();
version++;
}
/// <summary>The revolver hit <paramref name="victim"/> (OnProjectileHit runs on every device; the owner applies it).</summary>
public void ReportShot(StageTimePlayer shooter, StageTimePlayer victim)
{
if (!Networking.IsOwner(gameObject) || phase != Playing || shooter == null || victim == null) return;
int killer = SlotOf(shooter.playerId), target = SlotOf(victim.playerId);
if (killer < 0 || target < 0 || states[killer] != Alive || states[target] != Alive || shooter.playerId != gunBearer) return;
Kill(target, Shot);
if (roles[target] != Murderer && detectivePenalty)
{
Kill(killer, Punished);
Announce(EventWrongTarget);
}
CheckWin();
version++;
}
/// <summary>A living innocent picked up the dropped revolver.</summary>
public void ReportGunClaim(int playerId, int reportRound)
{
if (!Networking.IsOwner(gameObject) || reportRound != round || !GunDropped()) return;
int slot = SlotOf(playerId);
if (slot < 0 || states[slot] != Alive || roles[slot] == Murderer) return;
gunBearer = playerId;
version++;
}
private void Kill(int slot, int cause)
{
states[slot] = cause;
if (ids[slot] - 1 != gunBearer) return;
gunBearer = -1;
Announce(EventGunDropped);
}
private void Announce(int code)
{
eventCode = code;
eventSeq++;
}
}
The weapons
Every weapon waits at its bearer's side, and only the bearer sees it. The bearer's device takes ownership of the
weapon so it can move it into the holster each frame. Other players see it only while it is drawn, and dropping it puts
it back at the bearer's side. Desktop players can only grab what is under the crosshair, so F (OnInputSecondaryUse)
draws the weapon with STPickup.PickUp() and F again puts it away. Between rounds its owner moves the weapon back to
where it started.
A knife kills in two ways:
- In VR, the blade is a trigger collider.
OnPlayerTriggerEnterfires when it touches another player's body or head, not just their feet. - On desktop, using the knife casts a short ray from the player's head with
STPhysics.Raycast. The ray ignores the knife the player is holding, so it reaches the player in front.
The revolver is a projectile launcher with Hit Players turned on. OnProjectileHit arrives on every device with
the same victim, so the owner of the game applies it directly, with no report needed.
A device that is not the game's owner reports a knife kill through the weapon's own synced fields. The game's owner
reads them in OnDeserialization. Network events take no parameters, so synced fields carry the details instead.
using StageTime.SDK;
using UnityEngine;
/// <summary>
/// A murderer's knife or the Detective's revolver (an ST Pickup). During a round it waits at its bearer's side, where
/// only they can see or grab it; once drawn everyone sees it, and dropping it puts it back at their side. Desktop
/// players can't aim at their own side, so F draws it (STPickup.PickUp) and F again puts it away. Knife kills: the
/// blade's trigger touching another player's head or body (OnPlayerTriggerEnter), or a stab with the use button (a short
/// STPhysics.Raycast, for desktop).
/// The bearer's device reports a kill to <see cref="MurderGame"/> through synced values, which the game's owner applies.
/// The revolver fires an ST Projectile Launcher; its hits reach every device through OnProjectileHit. When the Detective
/// dies the revolver drops where they fell, visible to all, and any living innocent can take it.
/// </summary>
public class MurderWeapon : StageTimeBehaviour
{
private const int ReportKnife = 1, ReportClaim = 2;
public MurderGame game;
public bool isRevolver;
[Tooltip("Knives only: which murderer carries it (0 = the first).")]
public int knifeIndex;
public STPickup pickup;
public STProjectileLauncher launcher;
[Tooltip("Hidden while the weapon is holstered, except for its bearer.")]
public Renderer[] renderers;
[Tooltip("Knives: where a stab starts in VR (its blue Z axis points along the blade).")]
public Transform tip;
public AudioSource sound;
public AudioClip drawClip, swishClip;
[Tooltip("Where the holster sits, relative to the bearer's feet and facing.")]
public Vector3 holsterOffset = new Vector3(0.28f, 0.95f, 0.3f);
public float stabReachVR = 0.5f;
public float stabReachDesktop = 1.9f;
public float stabCooldown = 0.8f;
[Synced] private int reportKind;
[Synced] private int reportFrom;
[Synced] private int reportTarget;
[Synced] private int reportRound;
[Synced] private int reportSeq;
private int handledSeq, lastBearer = -1;
private bool shown = true, parked;
private float nextStab;
private Vector3 home;
private Quaternion homeRotation;
private void Start()
{
home = transform.position;
homeRotation = transform.rotation;
handledSeq = reportSeq;
Show(false);
}
private void Update()
{
StageTimePlayer local = Networking.LocalPlayer;
int bearer = isRevolver ? game.GunBearer() : game.KnifeBearer(knifeIndex);
bool dropped = isRevolver && game.GunDropped();
bool mine = bearer == local.playerId;
bool held = pickup.IsHeld;
bool eligible = dropped && game.IsAlive(local.playerId) && game.RoleOf(local.playerId) != MurderGame.Murderer;
if (isRevolver && lastBearer == local.playerId && !mine && game.Phase() == MurderGame.Playing && Networking.IsOwner(gameObject))
{
// We just lost the revolver (we died): leave it on the floor where we fell, for an innocent to find.
if (held)
{
pickup.Drop(); // place it once the hand has let go
return;
}
transform.position = local.GetPosition() + Vector3.up * 0.04f;
transform.rotation = Quaternion.Euler(0f, local.GetRotation().eulerAngles.y + 90f, 90f);
}
lastBearer = bearer;
Show(held || mine || dropped);
pickup.pickupable = mine || eligible;
if (held && pickup.currentPlayer.isLocal && !mine && !eligible) pickup.Drop(); // the round ended in our hand
if (mine && !held)
{
if (!Networking.IsOwner(gameObject)) Networking.SetOwner(local, gameObject);
Quaternion facing = Quaternion.Euler(0f, local.GetRotation().eulerAngles.y, 0f);
transform.position = local.GetPosition() + facing * holsterOffset;
transform.rotation = facing * Quaternion.Euler(isRevolver ? 0f : 90f, 0f, 0f);
parked = false;
}
else if (bearer < 0 && !dropped && !held && !parked && Networking.IsOwner(gameObject))
{
// Back to storage between rounds. The owner moves it, like the holster, and the pickup syncs that.
transform.position = home;
transform.rotation = homeRotation;
parked = true;
}
}
private void Show(bool visible)
{
if (visible == shown) return;
shown = visible;
for (int i = 0; i < renderers.Length; i++) renderers[i].enabled = visible;
}
public override void OnPickup()
{
if (sound != null && drawClip != null) sound.PlayOneShot(drawClip);
if (isRevolver && game.GunDropped()) Report(ReportClaim, Networking.LocalPlayer.playerId);
}
/// <summary>Desktop: F draws the weapon from your side, and F again puts it back.</summary>
public override void OnInputSecondaryUse(bool value, STInputArgs args)
{
StageTimePlayer local = Networking.LocalPlayer;
if (!value || local.IsUserInVR()) return;
if (pickup.IsHeld && pickup.currentPlayer.isLocal) pickup.Drop();
else if ((isRevolver ? game.GunBearer() : game.KnifeBearer(knifeIndex)) == local.playerId) pickup.PickUp();
}
public override void OnPickupUseDown()
{
StageTimePlayer local = Networking.LocalPlayer;
if (isRevolver)
{
if (game.GunBearer() == local.playerId && game.IsAlive(local.playerId)) launcher.Fire();
return;
}
if (sound != null && swishClip != null) sound.PlayOneShot(swishClip);
bool vr = local.IsUserInVR();
Vector3 origin = vr ? tip.position : local.GetHeadPosition();
Vector3 direction = vr ? tip.forward : local.GetHeadRotation() * Vector3.forward;
STRaycastHit hit = STPhysics.Raycast(origin, direction, vr ? stabReachVR : stabReachDesktop);
if (hit != null && hit.player != null) TryStab(hit.player);
}
public override void OnPlayerTriggerEnter(StageTimePlayer player)
{
if (!isRevolver) TryStab(player);
}
public override void OnProjectileHit(STProjectileHit hit)
{
if (hit.player != null) game.ReportShot(hit.shooter, hit.player);
}
private void TryStab(StageTimePlayer victim)
{
StageTimePlayer local = Networking.LocalPlayer;
if (victim == null || victim.isLocal || !pickup.IsHeld || !pickup.currentPlayer.isLocal) return;
if (game.KnifeBearer(knifeIndex) != local.playerId || !game.IsAlive(victim.playerId) || Time.time < nextStab) return;
nextStab = Time.time + stabCooldown;
Report(ReportKnife, victim.playerId);
}
/// <summary>The game's owner applies it straight away; anyone else syncs it (we hold the weapon, so we own it).</summary>
private void Report(int kind, int target)
{
int from = Networking.LocalPlayer.playerId;
if (Networking.IsOwner(game.gameObject))
{
Apply(kind, from, target, game.Round());
return;
}
if (!Networking.IsOwner(gameObject)) Networking.SetOwner(Networking.LocalPlayer, gameObject);
reportKind = kind;
reportFrom = from;
reportTarget = target;
reportRound = game.Round();
reportSeq++;
handledSeq = reportSeq;
}
public override void OnDeserialization()
{
if (reportSeq == handledSeq) return;
handledSeq = reportSeq;
Apply(reportKind, reportFrom, reportTarget, reportRound);
}
private void Apply(int kind, int from, int target, int round)
{
if (kind == ReportKnife) game.ReportKnife(from, target, round);
else if (kind == ReportClaim) game.ReportGunClaim(target, round);
}
}
What each device shows
MurderPresenter compares the game's synced state with what it showed last time. From the difference it decides
what to play: the round start, the private role reveal, a body falling, a death sting or the result. It also
teleports the local player into the house and back to the lobby. Nothing in it is synced.
using StageTime.SDK;
using TMPro;
using UnityEngine;
/// <summary>
/// What each device does with <see cref="MurderGame"/>'s synced state: deals the local player into the house with a
/// private role reveal, plays kills and results, returns the dead to the lobby, and keeps the lobby's status board and
/// queue lectern up to date. Nothing here is synced; every device derives it from the game, which it polls through
/// MurderGame.Version (the game never calls this script, as a script must not be called back while it is running).
/// </summary>
public class MurderPresenter : StageTimeBehaviour
{
public MurderGame game;
public STQueue queue;
public MurderHud hud;
[Tooltip("Where players start in the house; slots are spread over them each round.")]
public Transform[] houseSpawns;
[Tooltip("Where players return in the lobby.")]
public Transform[] lobbySpawns;
public float revealSeconds = 4f;
[Header("Lobby")]
public TMP_Text statusText;
public TMP_Text queueText;
public TMP_Text queueButtonText;
[Header("Sound")]
[Tooltip("Plays 2D stingers for this device.")]
public AudioSource ui;
[Tooltip("A 3D source moved to where a player falls.")]
public AudioSource world;
public AudioClip roundStart, roleMurderer, roleDetective, roleBystander, death, winMurderers, winInnocents;
public AudioClip queueJoin, queueLeave, tick, knifeStab, bodyFall;
[Header("Colours")]
public Color murdererColour = new Color(0.86f, 0.16f, 0.14f);
public Color detectiveColour = new Color(0.36f, 0.62f, 1f);
public Color bystanderColour = new Color(0.93f, 0.88f, 0.78f);
private readonly int[] lastStates = new int[MurderGame.MaxPlayers];
private bool initialised;
private int lastRound, lastPhase, lastEventSeq, lastSecond = -1, returnRound = -1, lastVersion;
private string summary = "";
// ---- state changes --------------------------------------------------------------------------------------------
public override void OnQueueChanged() => RefreshQueue();
/// <summary>Reacts to the game's state; runs when <see cref="MurderGame.Version"/> changes.</summary>
private void Refresh()
{
int phase = game.Phase();
StageTimePlayer local = Networking.LocalPlayer;
int mySlot = game.SlotOf(local.playerId);
if (!initialised)
{
initialised = true;
lastRound = game.Round();
lastPhase = phase;
lastEventSeq = game.EventSeq();
for (int i = 0; i < lastStates.Length; i++) lastStates[i] = game.StateAt(i);
}
if (game.Round() != lastRound && phase >= MurderGame.Playing)
{
lastRound = game.Round();
for (int i = 0; i < lastStates.Length; i++) lastStates[i] = MurderGame.Alive;
RoundStarted(local, mySlot);
}
if (phase >= MurderGame.Playing)
{
for (int i = 0; i < lastStates.Length; i++)
{
int state = game.StateAt(i);
if (state != lastStates[i] && lastStates[i] == MurderGame.Alive) PlayerFell(i, state, local);
lastStates[i] = state;
}
}
if (game.EventSeq() != lastEventSeq)
{
lastEventSeq = game.EventSeq();
if (game.IsAlive(local.playerId)) Announce(game.EventCode());
}
if (phase == MurderGame.Ended && lastPhase != MurderGame.Ended) RoundEnded(local, mySlot);
lastPhase = phase;
ShowStatus();
RefreshQueue();
}
private void RoundStarted(StageTimePlayer local, int mySlot)
{
Play(roundStart);
if (mySlot < 0) return;
int entry = queue.IndexOf(local);
if (entry >= 0) queue.Remove(entry);
Transform spawn = houseSpawns[(mySlot + game.SpawnOffset()) % houseSpawns.Length];
local.TeleportTo(spawn.position, spawn.rotation);
local.Immobilize(true);
SendCustomEventDelayedSeconds(nameof(EndReveal), revealSeconds);
int role = game.RoleAt(mySlot);
if (role == MurderGame.Murderer)
{
Play(roleMurderer);
hud.Show("MURDERER", "Kill every innocent. Grab your knife: it waits at your side.\nOnly you can see it until you draw it.", murdererColour, revealSeconds + 2f);
}
else if (role == MurderGame.Detective)
{
Play(roleDetective);
hud.Show("DETECTIVE", "Find the murderers and shoot them. Your revolver waits at your side.\nShoot an innocent and you die too.", detectiveColour, revealSeconds + 2f);
}
else
{
Play(roleBystander);
hud.Show("BYSTANDER", "Survive. Stay with others and watch who goes quiet.\nIf the revolver falls, you can pick it up.", bystanderColour, revealSeconds + 2f);
}
}
public void EndReveal()
{
if (game.IsAlive(Networking.LocalPlayer.playerId)) Networking.LocalPlayer.Immobilize(false);
}
private void PlayerFell(int slot, int cause, StageTimePlayer local)
{
StageTimePlayer victim = StageTimePlayer.GetPlayerById(game.PlayerIdAt(slot));
if (victim == null || cause == MurderGame.Gone) return;
world.transform.position = victim.GetPosition() + Vector3.up;
if (cause == MurderGame.Knifed) world.PlayOneShot(knifeStab);
world.PlayOneShot(bodyFall);
if (!victim.isLocal) return;
Play(death);
local.Immobilize(true);
if (cause == MurderGame.Punished)
hud.Show("YOU SHOT AN INNOCENT", "Your guilt was fatal. Watch the rest from the lobby.", detectiveColour, 3f);
else
hud.Show("YOU WERE KILLED", cause == MurderGame.Shot ? "The Detective's bullet found you." : "A knife, out of the dark.", murdererColour, 3f);
returnRound = game.Round();
SendCustomEventDelayedSeconds(nameof(ReturnToLobby), 3f);
}
private void Announce(int code)
{
if (code == MurderGame.EventWrongTarget)
hud.Show("AN INNOCENT WAS SHOT", "The Detective is dead. Their revolver lies where they fell.", detectiveColour, 4f);
else if (code == MurderGame.EventGunDropped)
hud.Show("THE DETECTIVE IS DOWN", "Their revolver lies where they fell. Any innocent can take it.", detectiveColour, 4f);
}
private void RoundEnded(StageTimePlayer local, int mySlot)
{
bool murderers = game.Winner() == MurderGame.MurderersWin;
Play(murderers ? winMurderers : winInnocents);
summary = (murderers ? "Last round: the murderers won." : "Last round: the innocents survived.") + "\n" + Names(MurderGame.Murderer, "Murderer") + " " + Names(MurderGame.Detective, "Detective");
if (mySlot < 0 || game.StateAt(mySlot) != MurderGame.Alive) return;
bool won = murderers == (game.RoleAt(mySlot) == MurderGame.Murderer);
hud.Show(murderers ? "THE MURDERERS WIN" : "THE INNOCENTS SURVIVE", (won ? "You won. " : "You lost. ") + Names(MurderGame.Murderer, "Murderer"), murderers ? murdererColour : bystanderColour, 5f);
local.Immobilize(true);
returnRound = game.Round();
SendCustomEventDelayedSeconds(nameof(ReturnToLobby), 5f);
}
public void ReturnToLobby()
{
if (returnRound != game.Round()) return;
returnRound = -1;
StageTimePlayer local = Networking.LocalPlayer;
Transform spawn = lobbySpawns[(local.playerId & 0x7fff) % lobbySpawns.Length];
local.TeleportTo(spawn.position, spawn.rotation);
local.ResetMovement();
}
private string Names(int role, string label)
{
string names = "";
int count = 0;
for (int i = 0; i < MurderGame.MaxPlayers; i++)
{
if (game.RoleAt(i) != role) continue;
StageTimePlayer player = StageTimePlayer.GetPlayerById(game.PlayerIdAt(i));
if (player == null) continue;
names += (count++ > 0 ? ", " : "") + player.displayName;
}
if (count == 0) return "";
return label + (count > 1 ? "s: " : ": ") + names;
}
private void Play(AudioClip clip)
{
if (clip != null) ui.PlayOneShot(clip);
}
// ---- lobby boards ---------------------------------------------------------------------------------------------
private void Update()
{
int version = game.Version();
if (version != lastVersion)
{
lastVersion = version;
Refresh();
}
int second = (int)game.SecondsLeft();
if (second == lastSecond) return;
lastSecond = second;
ShowStatus();
StageTimePlayer local = Networking.LocalPlayer;
if (game.Phase() == MurderGame.Countdown && second < 5 && queue.IndexOf(local) >= 0) Play(tick);
if (game.Phase() == MurderGame.Playing && game.IsAlive(local.playerId)) hud.SetStatus(RoleName(game.RoleOf(local.playerId)) + " " + Clock(second));
else hud.SetStatus("");
}
private void ShowStatus()
{
int phase = game.Phase();
string text;
if (phase == MurderGame.Waiting)
text = "<size=130%>Waiting for players</size>\n" + queue.count + " of " + game.minPlayers + " needed in the queue.\nJoin at the lectern by the door.";
else if (phase == MurderGame.Countdown)
text = "<size=130%>Next round in " + (int)game.SecondsLeft() + "</size>\n" + queue.count + " players queued.";
else if (phase == MurderGame.Playing)
text = "<size=130%>Round in progress " + Clock((int)game.SecondsLeft()) + "</size>\n" + game.CountAlive(false) + " innocents and " + game.CountAlive(true) + (game.CountAlive(true) == 1 ? " murderer" : " murderers") + " alive.\nWatch the map. Queue now for the next round.";
else
text = "<size=130%>" + (game.Winner() == MurderGame.MurderersWin ? "The murderers win" : "The innocents survive") + "</size>";
if (phase != MurderGame.Ended && summary.Length > 0) text += "\n\n<size=80%><alpha=#AA>" + summary + "</size>";
else if (phase == MurderGame.Ended) text += "\n" + summary;
statusText.text = text;
}
public void RefreshQueue()
{
string list = "";
for (int i = 0; i < queue.count; i++)
{
StageTimePlayer player = queue.GetPlayer(i);
if (player != null) list += (i + 1) + ". " + player.displayName + (player.isLocal ? " <alpha=#88>(you)" : "") + "<alpha=#FF>\n";
}
queueText.text = list.Length > 0 ? list : "<alpha=#88>Nobody is queued yet.";
StageTimePlayer local = Networking.LocalPlayer;
if (game.IsAlive(local.playerId)) queueButtonText.text = "You are in the house";
else queueButtonText.text = queue.IndexOf(local) >= 0 ? "Leave the queue" : "Join the next round";
}
/// <summary>The lectern button.</summary>
public void ToggleQueue()
{
StageTimePlayer local = Networking.LocalPlayer;
if (game.IsAlive(local.playerId)) return;
int entry = queue.IndexOf(local);
if (entry >= 0)
{
queue.Remove(entry);
Play(queueLeave);
}
else
{
queue.Request(0, "");
Play(queueJoin);
}
}
private string Clock(int seconds) => (seconds / 60) + ":" + (seconds % 60).ToString("00");
private string RoleName(int role) => role == MurderGame.Murderer ? "MURDERER" : role == MurderGame.Detective ? "DETECTIVE" : "BYSTANDER";
}
The head-following panel shows each player their role and private messages. Every device moves its own copy, so only that player sees it.
using StageTime.SDK;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// A small world-space panel that floats in front of the local player's eyes for private messages (role reveal,
/// death, results) plus a faint status line (role and time left). It eases after the head rather than sticking to it,
/// which is kinder in VR. Only this device sees it, as every device moves its own copy.
/// </summary>
public class MurderHud : StageTimeBehaviour
{
public TMP_Text title;
public TMP_Text body;
public TMP_Text status;
public Image backdrop;
public float distance = 1.4f;
[Tooltip("How far below eye level the panel sits, in metres.")]
public float drop = 0.12f;
public float follow = 6f;
private float showUntil, shownAt;
private float backdropAlpha = 0.8f;
private Color titleColour;
private void Start()
{
backdropAlpha = backdrop.color.a;
SetAlpha(0f);
status.text = "";
}
/// <summary>Shows a message for <paramref name="seconds"/>, fading in and out.</summary>
public void Show(string heading, string text, Color colour, float seconds)
{
title.text = heading;
body.text = text;
titleColour = colour;
shownAt = Time.time;
showUntil = Time.time + seconds;
Snap();
}
public void SetStatus(string text) => status.text = text;
private void Update()
{
float alpha = Mathf.Clamp01((Time.time - shownAt) * 4f) * Mathf.Clamp01((showUntil - Time.time) * 1.5f);
SetAlpha(alpha);
Place(Time.deltaTime * follow);
}
private void Snap() => Place(1f);
private void Place(float t)
{
StageTimePlayer local = Networking.LocalPlayer;
Quaternion head = local.GetHeadRotation();
Quaternion yaw = Quaternion.Euler(0f, head.eulerAngles.y, 0f);
Vector3 target = local.GetHeadPosition() + yaw * Vector3.forward * distance + Vector3.down * drop;
transform.position = Vector3.Lerp(transform.position, target, Mathf.Clamp01(t));
transform.rotation = Quaternion.Slerp(transform.rotation, yaw, Mathf.Clamp01(t));
}
private void SetAlpha(float alpha)
{
Color c = titleColour;
c.a = alpha;
title.color = c;
Color b = body.color;
b.a = alpha;
body.color = b;
Color d = backdrop.color;
d.a = alpha * backdropAlpha;
backdrop.color = d;
}
}
The spectator map
The map image covers a known rectangle of the house, so a player's position maps straight onto it. Dots update ten times a second and glide between updates. Roles are shown because only spectators in the lobby can see the map.
using StageTime.SDK;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// The lobby's live map of the house for players waiting or dead: a dot and name for every living player in the round,
/// coloured by role (spectators may know; the living can't see the lobby). Dots glide between updates, which run ten
/// times a second. The map image must cover <see cref="worldMin"/>..<see cref="worldMax"/> (x, z) exactly.
/// </summary>
public class MurderMinimap : StageTimeBehaviour
{
public MurderGame game;
public MurderPresenter presenter;
[Tooltip("One per round slot (16), children of the map: an Image dot with a TMP name label under it.")]
public Transform[] dots;
public Image[] dotImages;
public TMP_Text[] labels;
public TMP_Text caption;
[Tooltip("World x/z covered by the map image.")]
public Vector2 worldMin = new Vector2(-16f, -12f);
public Vector2 worldMax = new Vector2(16f, 12f);
[Tooltip("The map's size in its own (local) units.")]
public Vector2 mapSize = new Vector2(3.2f, 2.4f);
public float smoothing = 12f;
private readonly Vector3[] targets = new Vector3[MurderGame.MaxPlayers];
private readonly bool[] visible = new bool[MurderGame.MaxPlayers];
private float nextSample;
private int shownRound = -1, shownPhase = -1;
private void Start()
{
for (int i = 0; i < dots.Length; i++) dots[i].gameObject.SetActive(false);
}
private void Update()
{
if (Time.time >= nextSample)
{
nextSample = Time.time + 0.1f;
Sample();
}
float t = Mathf.Clamp01(Time.deltaTime * smoothing);
for (int i = 0; i < dots.Length; i++)
if (visible[i]) dots[i].localPosition = Vector3.Lerp(dots[i].localPosition, targets[i], t);
}
private void Sample()
{
bool playing = game.Phase() == MurderGame.Playing;
if (game.Round() != shownRound || game.Phase() != shownPhase) Relabel(playing);
for (int i = 0; i < dots.Length; i++)
{
StageTimePlayer player = playing && game.StateAt(i) == MurderGame.Alive ? StageTimePlayer.GetPlayerById(game.PlayerIdAt(i)) : null;
bool show = player != null;
if (show)
{
Vector3 p = player.GetPosition();
targets[i] = new Vector3(
(Mathf.InverseLerp(worldMin.x, worldMax.x, p.x) - 0.5f) * mapSize.x,
(Mathf.InverseLerp(worldMin.y, worldMax.y, p.z) - 0.5f) * mapSize.y,
0f);
if (!visible[i]) dots[i].localPosition = targets[i];
}
if (show != visible[i])
{
visible[i] = show;
dots[i].gameObject.SetActive(show);
}
}
}
private void Relabel(bool playing)
{
shownRound = game.Round();
shownPhase = game.Phase();
caption.text = playing ? "LIVE · " + "<color=#DC2A24>murderer</color> <color=#5C9EFF>detective</color> <color=#EDE0C7>bystander</color>" : "The house is quiet.";
if (!playing) return;
for (int i = 0; i < dots.Length; i++)
{
StageTimePlayer player = StageTimePlayer.GetPlayerById(game.PlayerIdAt(i));
int role = game.RoleAt(i);
Color colour = role == MurderGame.Murderer ? presenter.murdererColour : role == MurderGame.Detective ? presenter.detectiveColour : presenter.bystanderColour;
dotImages[i].color = colour;
labels[i].text = player != null ? player.displayName : "";
labels[i].color = colour;
}
}
}
The storm
Each 20-second window of the room clock is hashed to decide whether lightning strikes and when. Every device works this out from the same clock, so the flash and the thunder line up for everyone without any syncing.
using StageTime.SDK;
using UnityEngine;
/// <summary>
/// Lightning and thunder over the mansion. The schedule comes from the room clock, so every player sees the same
/// flash at the same moment without any networking: each 20-second window holds one strike at a pseudo-random time,
/// a double flicker of light followed by thunder after a short delay. The moon itself is baked; the flash is a separate
/// realtime light without shadows that is switched on only for the half second it lasts, so it costs nothing otherwise.
/// </summary>
public class MurderStorm : StageTimeBehaviour
{
[Tooltip("A realtime light without shadows, inactive in the scene; switched on only during a flash.")]
public Light lightning;
[Tooltip("Light intensity at the peak of a flash.")]
public float flashIntensity = 5f;
public AudioSource thunder;
public AudioClip[] thunderClips;
public float window = 20f;
private int playedWindow = -1;
private bool lit;
private void Update()
{
double now = Networking.GetServerTimeInSeconds();
int index = (int)(now / window);
int hash = Hash(index);
float strike = 2f + (hash & 1023) / 1023f * (window - 6f);
float since = (float)(now - index * (double)window) - strike;
// Two quick flashes: 0..0.12 s and 0.22..0.45 s.
float flash = since < 0f ? 0f : since < 0.12f ? 1f : since < 0.22f ? 0.15f : since < 0.45f ? 0.7f * (1f - (since - 0.22f) / 0.23f) : 0f;
if ((flash > 0f) != lit)
{
lit = flash > 0f;
lightning.gameObject.SetActive(lit);
}
if (lit) lightning.intensity = flash * flashIntensity;
float delay = 0.8f + ((hash >> 10) & 255) / 255f * 1.8f;
if (since >= delay && playedWindow != index && thunderClips.Length > 0)
{
playedWindow = index;
if (since < delay + 1f) thunder.PlayOneShot(thunderClips[(hash >> 18) % thunderClips.Length]);
}
}
private int Hash(int x)
{
x ^= x >> 16;
x *= 0x7feb352d;
x ^= x >> 15;
x *= 0x6a09e667;
x ^= x >> 16;
return x & 0x7fffffff;
}
}