PlayerAbilities.cs

Player abilities component for a multiplayer survivor-style game. Handles flashlight toggle, speed booster consumable, close-call adrenaline boost, parkour flow combo tracking, emote/taunt, and a deployable barrier, with cooldown/progress values exposed for the HUD.

Networking
🐞 CreateFlashlightLight runs in OnStart without an IsProxy check and parents the SpotLight to the local Scene.Camera, and the sync block in OnUpdate runs for proxies too, so a remote player's synced IsFlashlightOn turns on a light at your own camera.
🐞 The fallback barrier path builds the object with Scene.CreateObject and never calls NetworkSpawn, while the prefab path does, so that barrier and its delayed Destroy only exist on the owner's client.
using Sandbox;
using Sandbox.Citizen;
using System;
using System.Threading.Tasks;

public sealed class PlayerAbilities : Component
{
	public static PlayerAbilities LocalInstance { get; private set; }

	[Property] public GameObject HeavyObjectPrefab { get; set; }

	// Flashlight System
	[Sync] public bool IsFlashlightOn { get; set; } = false;
	[Property] public string FlashlightClickSound { get; set; } = "music/buttonhover.sound";

	// Speed Juice Consumable Booster (Key 1)
	[Property] public float SpeedJuiceCooldown { get; set; } = 15f;
	[Property] public float SpeedJuiceDuration { get; set; } = 6f;
	[Property] public float SpeedJuiceMultiplier { get; set; } = 1.30f;
	[Sync] public bool IsSpeedJuiceActive { get; private set; } = false;
	[Sync] private TimeSince _speedJuiceActiveTimer { get; set; } = 0f;
	private TimeSince _timeSinceSpeedJuice = 100f;

	// Emote / Taunt System (Key G)
	[Sync] public bool IsEmoting { get; private set; } = false;
	[Property] public string EmoteSound { get; set; } = "music/buttonhover.sound";

	// Barrier / Decoy (RMB)
	[Property] public float BarrierCooldown { get; set; } = 8f;
	private TimeSince _timeSinceBarrier = 100f;

	// Sound & Feedback
	[Property] public string BoostSound { get; set; } = "music/buttonhover.sound";

	// Near-Miss / Close Call Adrenaline Boost
	public bool IsAdrenalineActive { get; private set; } = false;
	[Sync] private TimeSince _adrenalineTimer { get; set; } = 100f;
	private float _adrenalineDuration = 1.5f;
	private float _adrenalineMultiplier = 1.10f;

	// Parkour "Flow" Combo Multiplier (5s decay window)
	[Property] public float FlowDecayWindow { get; set; } = 5.0f;
	[Sync] public int FlowComboCount { get; private set; } = 0;
	[Sync] public float FlowMultiplier { get; private set; } = 1.0f;
	[Sync] public string LastFlowActionLabel { get; private set; } = "";
	[Sync] private TimeSince _flowDecayTimer { get; set; } = 100f;
	public float FlowTimeRemaining => FlowComboCount > 0 ? MathF.Max( 0f, FlowDecayWindow - (float)_flowDecayTimer ) : 0f;
	public float FlowProgress => FlowComboCount > 0 ? MathX.Clamp( FlowTimeRemaining / MathF.Max( 0.01f, FlowDecayWindow ), 0f, 1f ) : 0f;

	public float SpeedJuiceCooldownProgress => MathX.Clamp( _timeSinceSpeedJuice / MathF.Max( 0.01f, SpeedJuiceCooldown ), 0f, 1f );
	public float SpeedJuiceRemaining => MathF.Max( 0f, SpeedJuiceDuration - (float)_speedJuiceActiveTimer );
	public float BarrierCooldownProgress => MathX.Clamp( _timeSinceBarrier / MathF.Max( 0.01f, BarrierCooldown ), 0f, 1f );

	private PlayerHealth _health;
	private EvadeMovement _evadeMovement;
	private PlayerController _playerController;
	private SpotLight _spotLight;
	private GameObject _flashlightObj;

	private float _originalWalkSpeed = 220f;
	private float _originalSprintSpeed = 500f;

	protected override void OnStart()
	{
		_health = Components.Get<PlayerHealth>() ?? Components.GetInChildren<PlayerHealth>();
		_evadeMovement = Components.Get<EvadeMovement>() ?? Components.GetInChildren<EvadeMovement>();
		_playerController = Components.Get<PlayerController>() ?? Components.GetInChildren<PlayerController>();

		if ( _evadeMovement.IsValid() )
		{
			_originalWalkSpeed = _evadeMovement.WalkSpeed;
			_originalSprintSpeed = _evadeMovement.SprintSpeed;
		}

		if ( !IsProxy && ( _playerController.IsValid() || _health.IsValid() ) )
		{
			LocalInstance = this;
		}

		CreateFlashlightLight();
	}

	private void CreateFlashlightLight()
	{
		if ( _flashlightObj.IsValid() ) return;

		var cam = Scene.Camera?.GameObject ?? GameObject;
		_flashlightObj = Scene.CreateObject();
		_flashlightObj.Name = "Player_Flashlight";
		_flashlightObj.SetParent( cam );
		_flashlightObj.LocalPosition = new Vector3( 15f, 10f, -8f );
		_flashlightObj.LocalRotation = Rotation.Identity;

		_spotLight = _flashlightObj.Components.Create<SpotLight>();
		_spotLight.Radius = 1400f;
		_spotLight.LightColor = Color.FromRgb( 0xfff6e8 );
		_spotLight.Shadows = true;
		_spotLight.Enabled = IsFlashlightOn;
	}

	protected override void OnUpdate()
	{
		// Keep SpotLight state in sync with network state
		if ( _spotLight.IsValid() )
		{
			bool shouldBeOn = IsFlashlightOn && ( _health == null || !_health.IsDead );
			if ( _spotLight.Enabled != shouldBeOn )
			{
				_spotLight.Enabled = shouldBeOn;
			}
		}

		if ( IsProxy ) return;

		// Cancel abilities while Downed or Dead
		if ( _health.IsValid() && ( _health.IsDead || _health.IsDowned ) )
		{
			if ( IsSpeedJuiceActive )
			{
				DeactivateSpeedJuice();
			}
			if ( IsEmoting )
			{
				IsEmoting = false;
			}
			if ( IsFlashlightOn )
			{
				IsFlashlightOn = false;
			}
			if ( FlowComboCount > 0 )
			{
				ResetFlowCombo();
			}
			return;
		}

		// Flow combo 5-second decay window
		if ( FlowComboCount > 0 && _flowDecayTimer >= FlowDecayWindow )
		{
			ResetFlowCombo();
		}

		// Speed Juice duration tick
		if ( IsSpeedJuiceActive && _speedJuiceActiveTimer > SpeedJuiceDuration )
		{
			DeactivateSpeedJuice();
		}

		// Adrenaline duration tick
		if ( IsAdrenalineActive && _adrenalineTimer > _adrenalineDuration )
		{
			DeactivateAdrenaline();
		}

		// Cancel Emote if player starts moving
		if ( IsEmoting )
		{
			var move = Input.AnalogMove;
			if ( !move.IsNearlyZero() || Input.Pressed( "jump" ) )
			{
				IsEmoting = false;
			}
		}

		// 1. FLASHLIGHT (Key F)
		if ( Input.Pressed( "flashlight" ) )
		{
			ToggleFlashlight();
		}

		// 2. SPEED JUICE BOOSTER (Key 1 / Slot 1)
		if ( Input.Pressed( "slot1" ) )
		{
			TryActivateSpeedJuice();
		}

		// 3. EMOTE / TAUNT (Key G / Drop action)
		if ( Input.Pressed( "drop" ) || Input.Pressed( "emote" ) )
		{
			TryTriggerEmote();
		}

		// 4. DEPLOYABLE BARRIER (RMB)
		if ( Input.Pressed( "attack2" ) )
		{
			TryDeployBarrier();
		}
	}

	public void ToggleFlashlight()
	{
		var meta = MetaProgression.Instance;
		if ( meta != null && !meta.HasFlashlight )
		{
			Log.Info( "[PlayerAbilities] Flashlight is not owned yet in Shop!" );
			return;
		}

		IsFlashlightOn = !IsFlashlightOn;

		if ( !string.IsNullOrEmpty( FlashlightClickSound ) )
		{
			Sound.Play( FlashlightClickSound, WorldPosition );
		}

		if ( _spotLight.IsValid() )
		{
			_spotLight.Enabled = IsFlashlightOn;
		}
	}

	public void TryActivateSpeedJuice()
	{
		var meta = MetaProgression.Instance;
		if ( meta != null && !meta.HasSpeedJuice )
		{
			Log.Info( "[PlayerAbilities] Speed Juice is not unlocked in Shop!" );
			return;
		}

		if ( _timeSinceSpeedJuice < SpeedJuiceCooldown || IsSpeedJuiceActive ) return;
		if ( _health.IsValid() && ( _health.IsDead || _health.IsDowned ) ) return;

		IsSpeedJuiceActive = true;
		_speedJuiceActiveTimer = 0f;
		_timeSinceSpeedJuice = 0f;

		if ( _evadeMovement.IsValid() )
		{
			_originalWalkSpeed = _evadeMovement.WalkSpeed;
			_originalSprintSpeed = _evadeMovement.SprintSpeed;
			ApplyMovementSpeeds();
		}

		if ( !string.IsNullOrEmpty( BoostSound ) )
		{
			Sound.Play( BoostSound, WorldPosition );
		}

		CameraJuice.Instance?.Shake( 14f, 5f );
		Log.Info( "[PlayerAbilities] Speed Juice activated (+30% speed for 6s)!" );
	}

	private void DeactivateSpeedJuice()
	{
		IsSpeedJuiceActive = false;
		ApplyMovementSpeeds();
		Log.Info( "[PlayerAbilities] Speed Juice expired." );
	}

	[Rpc.Broadcast]
	public void TriggerCloseCallAdrenaline()
	{
		if ( IsProxy ) return;
		if ( _health.IsValid() && ( _health.IsDead || _health.IsDowned ) ) return;

		IsAdrenalineActive = true;
		_adrenalineTimer = 0f;

		ApplyMovementSpeeds();

		if ( !string.IsNullOrEmpty( BoostSound ) )
		{
			Sound.Play( BoostSound, WorldPosition );
		}

		CameraJuice.Instance?.Shake( 8f, 3f );

		// Award +15 coins and contract progress
		RegisterFlowAction( "CLOSE CALL" );
		MetaProgression.Instance?.AddCredits( 15 );
		MetaProgression.Instance?.ProgressContract( ContractType.CloseCalls, 1 );

		// Show notification popup on HUD
		PushHud.LocalInstance?.ShowCloseCallNotification( "+15 COINS // CLOSE CALL!" );

		Log.Info( "[PlayerAbilities] Near-Miss / Close Call triggered! Adrenaline boost (+10% for 1.5s)" );
	}

	public void RegisterFlowAction( string actionLabel )
	{
		if ( IsProxy ) return;
		if ( _health.IsValid() && ( _health.IsDead || _health.IsDowned ) ) return;

		FlowComboCount++;
		_flowDecayTimer = 0f;
		LastFlowActionLabel = actionLabel;

		FlowMultiplier = FlowComboCount switch
		{
			>= 7 => 3.0f,
			>= 4 => 2.0f,
			>= 2 => 1.5f,
			_ => 1.0f
		};

		MetaProgression.Instance?.UpdateBestFlowCombo( FlowComboCount );
	}

	public void ResetFlowCombo()
	{
		FlowComboCount = 0;
		FlowMultiplier = 1.0f;
		LastFlowActionLabel = "";
	}

	private void DeactivateAdrenaline()
	{
		IsAdrenalineActive = false;
		ApplyMovementSpeeds();
	}

	private void ApplyMovementSpeeds()
	{
		if ( !_evadeMovement.IsValid() ) return;

		float mult = 1.0f;
		if ( IsSpeedJuiceActive ) mult *= SpeedJuiceMultiplier;
		if ( IsAdrenalineActive ) mult *= _adrenalineMultiplier;

		_evadeMovement.WalkSpeed = _originalWalkSpeed * mult;
		_evadeMovement.SprintSpeed = _originalSprintSpeed * mult;
	}

	public void TryTriggerEmote()
	{
		if ( _health.IsValid() && ( _health.IsDead || _health.IsDowned ) ) return;

		IsEmoting = !IsEmoting;

		if ( IsEmoting )
		{
			BroadcastEmoteSound( WorldPosition );

#pragma warning disable CS0618
			var anim = Components.Get<CitizenAnimationHelper>() ?? Components.GetInChildren<CitizenAnimationHelper>();
			if ( anim.IsValid() )
			{
				anim.IsSitting = true;
				anim.Sitting = (CitizenAnimationHelper.SittingStyle)1;
			}
#pragma warning restore CS0618
			Log.Info( "[PlayerAbilities] Emoting started! Move to cancel." );
		}
		else
		{
#pragma warning disable CS0618
			var anim = Components.Get<CitizenAnimationHelper>() ?? Components.GetInChildren<CitizenAnimationHelper>();
			if ( anim.IsValid() )
			{
				anim.IsSitting = false;
			}
#pragma warning restore CS0618
		}
	}

	[Rpc.Broadcast]
	public void BroadcastEmoteSound( Vector3 pos )
	{
		if ( !string.IsNullOrEmpty( EmoteSound ) )
		{
			Sound.Play( EmoteSound, pos );
		}
	}

	public void TryDeployBarrier()
	{
		if ( _timeSinceBarrier < BarrierCooldown ) return;
		if ( _health.IsValid() && ( _health.IsDead || _health.IsDowned ) ) return;

		var spawnPos = WorldPosition + WorldTransform.Forward * 80f + Vector3.Up * 20f;

		if ( HeavyObjectPrefab.IsValid() )
		{
			var obj = HeavyObjectPrefab.Clone( spawnPos );
			if ( obj.IsValid() )
			{
				MapEventManager.Instance?.RegisterPhysics( obj );
				if ( Network.Active )
				{
					obj.NetworkSpawn();
				}
			}
			_timeSinceBarrier = 0f;
			Log.Info( "[PlayerAbilities] Barricade deployed!" );
		}
		else
		{
			var obj = Scene.CreateObject();
			obj.Name = "Evade_Barrier";
			obj.WorldPosition = spawnPos;

			var model = Model.Load( "models/dev/box.vmdl" );
			if ( model != null )
			{
				var r = obj.Components.Create<ModelRenderer>();
				r.Model = model;
				r.Tint = new Color( 0.2f, 0.6f, 1f, 0.8f );
			}

			var col = obj.Components.Create<BoxCollider>();
			col.Scale = new Vector3( 60f, 60f, 60f );

			var rb = obj.Components.Create<Rigidbody>();
			rb.MassOverride = 800f;

			_ = DestroyDelayed( obj, 10f );
			_timeSinceBarrier = 0f;
			Log.Info( "[PlayerAbilities] Barricade created!" );
		}

		if ( !string.IsNullOrEmpty( BoostSound ) )
		{
			Sound.Play( BoostSound, WorldPosition );
		}
	}

	private async Task DestroyDelayed( GameObject go, float delaySeconds )
	{
		await Task.DelaySeconds( delaySeconds );
		if ( go.IsValid() ) go.Destroy();
	}

	protected override void OnDestroy()
	{
		if ( IsSpeedJuiceActive )
		{
			DeactivateSpeedJuice();
		}
		if ( _flashlightObj.IsValid() )
		{
			_flashlightObj.Destroy();
		}
		if ( LocalInstance == this )
		{
			LocalInstance = null;
		}
		base.OnDestroy();
	}
}