A special level where countdowns drop the floor under the players, stage after stage.
The Random special level is a survival minigame built around a chain of LED countdowns. Players start on an upper platform. When the countdown hits 00:00, the pistons holding the floor move away and everyone falls to the next platform, where a new countdown starts. The last stage ends with a flag at the finish.
The game mode stays small. It only decides when the round is over and keeps track of how many sequences were completed. It counts sides, so it works with Team Match too.
// GM_Random: the round is over when one side (player or team) is left alive.
public override bool HasWinConditionBeenAchieved()
{
var nbPlayerLeftAlive = _gameStateReference.AliveSideCount;
return nbPlayerLeftAlive <= 1;
}
// Called by the countdown manager once the WHOLE sequence is done, not each stage.
public void OnCountdownFinished()
{
_isCountdownActive = false;
_currentCountdownIndex++;
}The core is the SequentialCountdownManager. A stage is a plain serializable class, so every part of the level that reacts to a countdown is assigned in the inspector.
// One stage = one LED countdown, one camera and what moves when it reaches 00:00.
[System.Serializable]
public class CountdownStage
{
public BasketLedCounter countdown;
public Unity.Cinemachine.CinemachineCamera stageCamera;
public List<SplineWaitParameter> splinesToActivateOnFinish; // pistons that retract
public float splineActivationDelay = 0f;
public List<FollowSpline> splinesToChangeSpeed; // things that speed up
public float countdownFinishedSpeed = 1f;
}The manager disables every counter at the start, then starts stage 0. When a counter finishes, it switches the camera, triggers the stage's pistons and starts the next stage. After the last one, it tells the game mode that the whole sequence is over.
// Each countdown starts only when the previous one finishes.
private void StartStage(int stageIndex)
{
_currentStageIndex = stageIndex;
var stage = stages[stageIndex];
stage.countdown.onCountdownFinished.AddListener(OnCurrentStageFinished);
stage.countdown.enabled = true;
stage.countdown.StartCountdown();
}
private void OnCurrentStageFinished()
{
var currentStage = stages[_currentStageIndex];
_completedStages = Mathf.Max(_completedStages, _currentStageIndex + 1);
SwitchCamera(currentStage); // this stage's camera gets priority 100
ActivatePistonsForStage(_currentStageIndex); // pistons retract, players fall
var nextStageIndex = _currentStageIndex + 1;
if (nextStageIndex < stages.Count) StartStage(nextStageIndex);
else OnAllStagesCompleted(); // tells GM_Random the sequence is over
}Making the floor disappear is two small loops: start the piston splines of this stage, and change the speed of anything that should react.
// What "the floor disappears" means in code.
foreach (var splineParam in stage.splinesToActivateOnFinish)
if (splineParam != null) splineParam.DynamicStart();
foreach (var followSpline in stage.splinesToChangeSpeed)
if (followSpline != null) followSpline.SetSplineSpeed(stage.countdownFinishedSpeed);PlayerPassTrigger speeds the pistons up once every living player has passed through a trigger zone, so a group that is fast is not forced to wait. Dead players are ignored, and it can only fire once.
// PlayerPassTrigger: when every ALIVE player went through, the pistons stop waiting.
private void CheckIfAllPlayersPassed()
{
var alivePlayers = GameObject.FindGameObjectsWithTag(playerTag)
.Where(player => player.activeInHierarchy) // dead players are not counted
.ToList();
var allPassed = alivePlayers.All(_playersPassed.Contains);
if (allPassed && alivePlayers.Count > 0) TriggerPistonSpeedUp();
}
private void TriggerPistonSpeedUp()
{
if (_hasTriggered) return; // only once
_hasTriggered = true;
foreach (var splineParam in splinesToModify)
if (splineParam != null) splineParam.SetWaitEndSpline(0f);
}The finish uses MultiWinnerFlag. The first player to touch it starts a timer. Anyone who touches it before the timer ends is added to the winners, and when the timer ends the round is closed with all of them.
// MultiWinnerFlag: the first player starts a timer, anyone arriving before it ends also wins.
private void OnTriggerEnter2D(Collider2D other)
{
if (_isFinished) return;
if (!other.TryGetComponent<PlayerPawn>(out var playerPawn)) return;
if (_winners.Contains(playerPawn)) return;
_winners.Add(playerPawn);
if (!_firstPlayerArrived)
{
_firstPlayerArrived = true;
StartCoroutine(EndGameAfterDelay());
}
}
private IEnumerator EndGameAfterDelay()
{
yield return new WaitForSeconds(waitEnding);
_isFinished = true;
var winnerControllers = _winners.Select(pawn => pawn.GetOwner()).Where(c => c != null).ToArray();
GameStateBase.Instance.RequestEndRound(winnerControllers);
}To end the round from a flag, I added a small public method on the game state. It works with any game state, so a level object does not have to know which mode is running.
// GameStateBase: a small public door so flags and triggers can end the round,
// whatever the game state is.
public void RequestEndRound(PlayerController[] winners)
{
EndRound(winners);
}Most of the work on this level was making sure it behaves when many things happen at once. Here are three problems and how the code solves them.
A countdown can be started again while it is still running, for example when stages are chained. The old timer kept going next to the new one. Now StartCountdown cancels the existing timer first.
// BUG: calling StartCountdown while a timer was already running left two timers alive.
// FIX: cancel the running timer before registering a new one.
public void StartCountdown()
{
if (_timer != null)
{
_timer.Cancel();
}
_currentTime = CountdownTime;
_timer = Timer.Register(1f, OnCooldownFinished, cancelOnSceneChange: false);
IsRunning = true;
}The manager subscribes to the finish event of every counter. If it is destroyed without unsubscribing, those events can call into an object that no longer exists. OnDestroy now removes every listener.
// BUG: listeners on the countdown events could outlive the manager.
// FIX: remove every listener when the manager is destroyed.
private void OnDestroy()
{
foreach (var stage in stages)
{
if (stage.countdown != null)
{
stage.countdown.onCountdownFinished.RemoveListener(OnCurrentStageFinished);
}
}
}In a survival round the winner is the last one alive. If the last two players die almost together, the order of the two deaths should not decide the winner. GS_Random waits for a short buffer and restarts it at each death, so a near-simultaneous death is treated as a tie.
// PROBLEM: two players can die within a split second of each other, and the order
// of the two deaths should not decide the winner.
// SOLUTION (GS_Random): wait a short buffer before deciding, and refresh it on every death.
protected override void HandlePlayerDeath(PlayerController playerController)
{
base.HandlePlayerDeath(playerController);
if (!IsCountdownFinished) return;
if (!GameModeBase.Instance.HasWinConditionBeenAchieved()) return;
// Nobody alive: check for a tie right away.
if (_alivePlayers.Count == 0)
{
EndRound(GetEndRoundBufferWinner(UnityEngine.Time.time).ToArray());
return;
}
// One side left: start (or refresh) the buffer to check for a tie later.
if (AliveSideCount == 1) RestartEndGameBuffer();
}