ShooterWeapon.cs

A weapon component for a shooter game. It handles player input to fire a pistol, performs a ray trace from the camera to detect hits, plays a shooting sound, and applies physics impulses to hit rigidbodies or ancestor rigidbodies.

File Access
using Sandbox;
using System.Linq;

public sealed class ShooterWeapon : Component
{
	[Property] public string WeaponName { get; set; } = "Pistol";
	[Property] public float DamageForce { get; set; } = 800f;
	[Property] public float FireRate { get; set; } = 0.25f;
	[Property] public float Range { get; set; } = 2000f;

	[Sync] private TimeSince _timeSinceLastShot { get; set; }

	protected override void OnUpdate()
	{
		if ( IsProxy ) return;

		var health = Components.Get<PlayerHealth>() ?? Components.GetInChildren<PlayerHealth>();
		if ( health.IsValid() && ( health.IsDead || health.IsDowned ) ) return;
		if ( health.IsValid() && health.IsRescuing ) return;

		if ( Input.Down( "attack1" ) && _timeSinceLastShot >= FireRate )
		{
			Shoot();
			_timeSinceLastShot = 0;
		}
	}

	private void Shoot()
	{
		var cam = Scene.Camera;
		if ( cam == null ) return;

		Vector3 startPos = cam.WorldPosition;
		Vector3 forwardDir = cam.WorldRotation.Forward;

		var tr = Scene.Trace.Ray( startPos, startPos + forwardDir * Range )
			.IgnoreGameObjectHierarchy( GameObject )
			.Run();

		Sound.Play( "rust_pistol.shoot", WorldPosition );

		if ( tr.Hit && tr.GameObject != null )
		{
			// 1. Проверяем напрямую точное попадание в Rigidbody
			if ( tr.Body != null )
			{
				tr.Body.ApplyImpulseAt( tr.EndPosition, forwardDir * DamageForce );
				return;
			}

			// 2. Ищем Rigidbody на текущем объекте или у его родителей
			var targetBody = tr.GameObject.Components.Get<Rigidbody>( true ) 
			                 ?? tr.GameObject.Components.GetInAncestors<Rigidbody>();

			if ( targetBody != null )
			{
				targetBody.ApplyImpulse( forwardDir * DamageForce );
			}
		}
	}
}