Map event manager for the arena game mode. Cycles random map-wide events (low gravity, slippery ice, strong wind, lights out) on a timer, applies the corresponding physics effects in OnFixedUpdate, and runs a sumo overtime phase that shrinks the arena and drops anvil or barrel hazards every few seconds. Lights-out disables scene lights, spawns red emergency point lights and swaps in a dark fog volume, then restores the originals.
using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public enum WeatherType
{
None,
LowGravity,
SlipperyIce,
StrongWind,
LightsOut,
Overtime
}
public sealed class MapEventManager : Component
{
public static MapEventManager Instance { get; private set; }
[Property] public float EventDuration { get; set; } = 12f;
[Property] public float LightsOutDuration { get; set; } = 20f;
[Property] public float EventInterval { get; set; } = 25f;
[Property] public float LowGravityForce { get; set; } = 450f;
[Property] public float WindForce { get; set; } = 400f;
[Property] public GameObject FallingAnvilPrefab { get; set; }
[Property] public GameObject FallingBarrelPrefab { get; set; }
public WeatherType CurrentEvent { get; private set; } = WeatherType.None;
public Vector3 CurrentWindDirection { get; private set; } = Vector3.Right;
public float TimeRemaining { get; private set; }
public bool IsOvertimeActive { get; private set; } = false;
[Sync] private TimeUntil _nextEventTime { get; set; }
[Sync] private TimeUntil _eventEndTime { get; set; }
private readonly List<CharacterController> _players = new();
private readonly List<Rigidbody> _rigidbodies = new();
private readonly List<Component> _dimmedLights = new();
private readonly List<GameObject> _emergencyLightObjects = new();
private GameObject _createdFogObj;
private bool _hadExistingFog = false;
private bool _prevFogEnabled = false;
private float _prevAttenuationDistance = 2000f;
private float _prevMaxOpacity = 0.6f;
private Color _prevFogColor = Color.Gray;
[Sync] private float _sumoRoundTimer { get; set; } = 0f;
[Sync] private TimeSince _timeSinceHazardSpawn { get; set; } = 0f;
protected override void OnAwake()
{
Instance = this;
_nextEventTime = EventInterval;
}
protected override void OnStart()
{
_players.AddRange( Scene.GetAllComponents<CharacterController>() );
_rigidbodies.AddRange( Scene.GetAllComponents<Rigidbody>() );
}
public void RegisterPlayerPhysics( CharacterController characterController, Rigidbody rigidbody )
{
if ( characterController.IsValid() && !_players.Contains( characterController ) )
{
_players.Add( characterController );
}
if ( rigidbody.IsValid() && !_rigidbodies.Contains( rigidbody ) )
{
_rigidbodies.Add( rigidbody );
}
}
public void RegisterPhysics( GameObject gameObject )
{
if ( !gameObject.IsValid() ) return;
RegisterPlayerPhysics(
gameObject.Components.Get<CharacterController>( true ),
gameObject.Components.Get<Rigidbody>( true ) );
}
protected override void OnUpdate()
{
if ( IsProxy ) return;
bool isEvadeMode = Scene.GetAllComponents<NextbotAI>().Any() || Scene.GetAllComponents<EvadeRoundManager>().Any();
bool isSumoMode = RoundManager.Instance != null && RoundManager.Instance.IsInRound;
// Sumo Overtime Check (>90 seconds)
if ( isSumoMode )
{
_sumoRoundTimer += Time.Delta;
if ( _sumoRoundTimer > 90f && !IsOvertimeActive )
{
TriggerSumoOvertime();
}
}
else
{
_sumoRoundTimer = 0f;
if ( IsOvertimeActive )
{
IsOvertimeActive = false;
if ( CurrentEvent == WeatherType.Overtime )
{
EndEvent();
}
}
}
// Active Event timer management
if ( CurrentEvent == WeatherType.None && _nextEventTime )
{
// For Evade mode: only trigger random events during the active survival phase
if ( isEvadeMode )
{
var evadeMgr = EvadeRoundManager.Instance;
if ( evadeMgr != null && evadeMgr.CurrentPhase != EvadePhase.Survival )
{
_nextEventTime = 5f;
return;
}
}
StartRandomEvent( isEvadeMode );
}
else if ( CurrentEvent != WeatherType.None )
{
TimeRemaining = _eventEndTime;
if ( _eventEndTime && CurrentEvent != WeatherType.Overtime )
{
EndEvent();
}
}
// Overtime periodic hazard drop
if ( IsOvertimeActive && _timeSinceHazardSpawn > 3.5f )
{
_timeSinceHazardSpawn = 0f;
SpawnOvertimeHazard();
}
}
protected override void OnFixedUpdate()
{
if ( CurrentEvent == WeatherType.None ) return;
if ( CurrentEvent == WeatherType.LowGravity )
{
foreach ( var cc in _players )
{
if ( cc.IsValid() )
{
cc.Velocity += Vector3.Up * LowGravityForce * Time.Delta;
}
}
foreach ( var rb in _rigidbodies )
{
if ( rb.IsValid() && !rb.IsProxy )
{
rb.ApplyImpulse( Vector3.Up * (rb.PhysicsBody.Mass * LowGravityForce * Time.Delta) );
}
}
}
else if ( CurrentEvent == WeatherType.StrongWind )
{
foreach ( var cc in _players )
{
if ( cc.IsValid() )
{
cc.Velocity += CurrentWindDirection * WindForce * Time.Delta;
}
}
foreach ( var rb in _rigidbodies )
{
if ( rb.IsValid() && !rb.IsProxy )
{
rb.ApplyImpulse( CurrentWindDirection * WindForce * 15f * Time.Delta );
}
}
}
else if ( CurrentEvent == WeatherType.SlipperyIce )
{
foreach ( var cc in _players )
{
if ( cc.IsValid() && cc.IsOnGround )
{
var vel = cc.Velocity;
vel.x *= 1.015f;
vel.y *= 1.015f;
cc.Velocity = vel;
}
}
}
}
private void StartRandomEvent( bool isEvadeMode )
{
List<WeatherType> availableEvents;
if ( isEvadeMode )
{
// LightsOut is weighted higher in Nextbot mode for thrilling horror atmosphere
availableEvents = new List<WeatherType>
{
WeatherType.LightsOut,
WeatherType.LightsOut,
WeatherType.LowGravity,
WeatherType.StrongWind,
WeatherType.SlipperyIce
};
}
else
{
availableEvents = new List<WeatherType>
{
WeatherType.LowGravity,
WeatherType.SlipperyIce,
WeatherType.StrongWind
};
}
CurrentEvent = availableEvents[Random.Shared.Next( availableEvents.Count )];
if ( CurrentEvent == WeatherType.LightsOut )
{
_eventEndTime = LightsOutDuration;
TriggerLightsOut( true );
}
else
{
_eventEndTime = EventDuration;
}
if ( CurrentEvent == WeatherType.StrongWind )
{
float angle = Random.Shared.NextSingle() * MathF.PI * 2f;
CurrentWindDirection = new Vector3( MathF.Cos( angle ), MathF.Sin( angle ), 0f ).Normal;
}
if ( Killfeed.Instance != null )
{
if ( CurrentEvent == WeatherType.LightsOut )
{
Killfeed.Instance.AddEntry( "EVENT", "ALL RUNNERS", "LIGHTS OUT! USE FLASHLIGHT [F]" );
}
else
{
Killfeed.Instance.AddEntry( "EVENT", "ARENA", $"{CurrentEvent.ToString().ToUpper()} ACTIVE!" );
}
}
Log.Info( $"[MapEventManager] Started map event: {CurrentEvent}" );
}
private void TriggerLightsOut( bool turnOff )
{
BroadcastLightsOutAtmosphere( turnOff );
}
[Rpc.Broadcast]
private void BroadcastLightsOutAtmosphere( bool turnOff )
{
if ( turnOff )
{
_dimmedLights.Clear();
// Disable directional & world point/spot lights that aren't player flashlights or Nextbot clustered lights
foreach ( var light in Scene.GetAllComponents<DirectionalLight>() )
{
if ( light.IsValid() && light.Enabled )
{
light.Enabled = false;
_dimmedLights.Add( light );
}
}
foreach ( var light in Scene.GetAllComponents<PointLight>() )
{
if ( light.IsValid() && light.Enabled &&
!light.GameObject.Name.Contains( "Flashlight" ) &&
!light.GameObject.Name.Contains( "Nextbot_ClusterLight" ) &&
!light.GameObject.Name.Contains( "EmergencyLight" ) )
{
light.Enabled = false;
_dimmedLights.Add( light );
}
}
foreach ( var light in Scene.GetAllComponents<SpotLight>() )
{
if ( light.IsValid() && light.Enabled && !light.GameObject.Name.Contains( "Flashlight" ) )
{
light.Enabled = false;
_dimmedLights.Add( light );
}
}
// Spawn Borealis clustered red emergency lights with fluorescent flicker
SpawnEmergencyLights();
ApplyPowerOutageFog( true );
Sound.Play( "music/buttonhover.sound" );
CameraJuice.Instance?.Shake( 15f );
}
else
{
// Restore dimmed lights
foreach ( var light in _dimmedLights )
{
if ( light.IsValid() )
{
if ( light is DirectionalLight dl ) dl.Enabled = true;
else if ( light is PointLight pl ) pl.Enabled = true;
else if ( light is SpotLight sl ) sl.Enabled = true;
}
}
_dimmedLights.Clear();
CleanupEmergencyLights();
ApplyPowerOutageFog( false );
Sound.Play( "music/buttonhover.sound" );
}
}
private void SpawnEmergencyLights()
{
CleanupEmergencyLights();
var spawnOrigin = Scene.GetAllComponents<SpawnPoint>().FirstOrDefault()?.WorldPosition ?? Vector3.Zero;
Vector3[] offsets = new[]
{
new Vector3( 320f, 320f, 180f ),
new Vector3( -360f, 240f, 180f ),
new Vector3( 0f, -380f, 180f )
};
for ( int i = 0; i < offsets.Length; i++ )
{
var lightObj = Scene.CreateObject();
lightObj.Name = $"EmergencyLight_{i}";
lightObj.WorldPosition = spawnOrigin + offsets[i];
var pt = lightObj.Components.Create<PointLight>();
pt.LightColor = Color.FromRgb( 0xdc2626 );
pt.Intensity = 3.6f;
pt.Radius = 900f;
pt.Shadows = false;
pt.FogStrength = 2.2f;
pt.AnimationEnabled = true;
pt.AnimationPattern = LightAnimationPattern.FluorescentFlicker;
pt.AnimationSpeed = 1.35f + i * 0.25f;
_emergencyLightObjects.Add( lightObj );
}
}
private void CleanupEmergencyLights()
{
foreach ( var obj in _emergencyLightObjects )
{
if ( obj.IsValid() ) obj.Destroy();
}
_emergencyLightObjects.Clear();
}
private void ApplyPowerOutageFog( bool enable )
{
var fog = Scene.GetAllComponents<Fog>().FirstOrDefault();
if ( enable )
{
if ( fog.IsValid() )
{
_hadExistingFog = true;
_prevFogEnabled = fog.FogEnabled;
_prevAttenuationDistance = fog.AttenuationDistance;
_prevMaxOpacity = fog.MaximumOpacity;
_prevFogColor = fog.Color;
}
else
{
_hadExistingFog = false;
_createdFogObj = Scene.CreateObject();
_createdFogObj.Name = "PowerOutage_FogVolume";
fog = _createdFogObj.Components.Create<Fog>();
}
fog.FogEnabled = true;
fog.DistanceEnabled = true;
fog.Mode = Sandbox.Rendering.FogMode.Exponential;
fog.AttenuationDistance = 580f;
fog.MaximumOpacity = 0.88f;
fog.ColorSource = FogColorSource.Constant;
fog.Color = Color.FromRgb( 0x160709 );
}
else
{
if ( _hadExistingFog && fog.IsValid() )
{
fog.FogEnabled = _prevFogEnabled;
fog.AttenuationDistance = _prevAttenuationDistance;
fog.MaximumOpacity = _prevMaxOpacity;
fog.Color = _prevFogColor;
}
else if ( _createdFogObj.IsValid() )
{
_createdFogObj.Destroy();
_createdFogObj = null;
}
}
}
private void TriggerSumoOvertime()
{
IsOvertimeActive = true;
CurrentEvent = WeatherType.Overtime;
_timeSinceHazardSpawn = 0f;
// Shrink platform faster
var shrinker = Scene.GetAllComponents<ArenaShrinker>().FirstOrDefault();
if ( shrinker.IsValid() )
{
shrinker.ShrinkInterval = MathF.Max( 4f, shrinker.ShrinkInterval * 0.4f );
}
CameraJuice.Instance?.Shake( 25f, 6f );
Sound.Play( "music/buttonhover.sound" );
if ( Killfeed.Instance != null )
{
Killfeed.Instance.AddEntry( "ALERT", "SUMO ARENA", "OVERTIME! RAPID COLLAPSE & HAZARDS!" );
}
Log.Info( "[MapEventManager] Sumo Overtime triggered!" );
}
private void SpawnOvertimeHazard()
{
var tiles = Scene.GetAllComponents<ArenaTile>().Where( t => t.IsValid() && !t.IsFalling ).ToList();
if ( tiles.Count == 0 ) return;
var targetTile = tiles[Random.Shared.Next( tiles.Count )];
Vector3 spawnPos = targetTile.WorldPosition + Vector3.Up * 700f + new Vector3( Random.Shared.Float( -50f, 50f ), Random.Shared.Float( -50f, 50f ), 0f );
// Spawn falling anvil or explosive barrel
if ( Random.Shared.Next( 2 ) == 0 && FallingAnvilPrefab.IsValid() )
{
var anvil = FallingAnvilPrefab.Clone( spawnPos );
RegisterPhysics( anvil );
}
else if ( FallingBarrelPrefab.IsValid() )
{
var barrel = FallingBarrelPrefab.Clone( spawnPos );
RegisterPhysics( barrel );
}
else
{
// Dynamic hazard box fallback
var hazardObj = Scene.CreateObject();
hazardObj.Name = "Overtime_Hazard";
hazardObj.WorldPosition = spawnPos;
var r = hazardObj.Components.Create<ModelRenderer>();
r.Model = Model.Load( "models/dev/box.vmdl" );
r.Tint = Color.Red;
var col = hazardObj.Components.Create<BoxCollider>();
col.Scale = new Vector3( 45f, 45f, 45f );
var rb = hazardObj.Components.Create<Rigidbody>();
rb.MassOverride = 600f;
var hz = hazardObj.Components.Create<HazardZone>();
hz.DamagePerTouch = 40f;
_ = DestroyDelayed( hazardObj, 12f );
}
}
private async Task DestroyDelayed( GameObject go, float delay )
{
await Task.DelaySeconds( delay );
if ( go.IsValid() ) go.Destroy();
}
private void EndEvent()
{
Log.Info( $"[MapEventManager] Ended event: {CurrentEvent}" );
if ( CurrentEvent == WeatherType.LightsOut )
{
TriggerLightsOut( false );
}
CurrentEvent = WeatherType.None;
_nextEventTime = EventInterval;
}
protected override void OnDestroy()
{
if ( CurrentEvent == WeatherType.LightsOut )
{
BroadcastLightsOutAtmosphere( false );
}
CleanupEmergencyLights();
if ( _createdFogObj.IsValid() )
{
_createdFogObj.Destroy();
_createdFogObj = null;
}
if ( Instance == this )
{
Instance = null;
}
}
}