A component that manages a player flashlight. It updates a SpotLight's position and rotation to follow the camera, toggles the light radius on input, and broadcasts RPCs to play a click sound and set the spotlight radius.
using Sandbox;
public class Flashlight : Component
{
[Property] public SpotLight Spotlight {get;set;} bool On;
GameObject c;
SoundEvent Click;
PlayerController Player_Controller;
protected override void OnStart()
{ if (IsProxy) return;
c = Scene.Camera.GameObject;
Click = ResourceLibrary.Get<SoundEvent>("prereqs/click/click.sound");
Player_Controller = GameObject.GetComponent<PlayerController>();
}
protected override void OnUpdate()
{ if (IsProxy || new Game.Overlay().IsPauseMenuOpen) return;
var z = Player_Controller.IsDucking ? 32 : 64;
Spotlight.GameObject.WorldPosition = WorldPosition + new Vector3(0, 0, z);
Spotlight.GameObject.WorldRotation = c.WorldRotation;
if (Input.Pressed("Flashlight"))
{
On = !On;
Set_Radius(Spotlight, (On ? 500 : 0));
PlaySound(Spotlight.GameObject, Click);
}
}
[Rpc.Broadcast]
public void PlaySound(GameObject go, SoundEvent s)
{go.PlaySound(s);}
[Rpc.Broadcast]
public void Set_Radius(SpotLight sl, float n)
{sl.Radius = n;}
}