Rampage/Giant/GiantFoes.cs

The town's vehicles for the Rampage giant mode. Tanks parked in town lob a single arcing shell at the giant that shakes the camera and knocks a rider off, and box-built news/army helicopters orbit the giant's head, take hits as IRampageTarget, fall and score when swatted, and return after a cooldown.

using System;
using System.Collections.Generic;

/// <summary>
/// What the town can do to a giant, which is not much: it is a victory lap and nothing can stop it.
///
///  - TANKS (the town parks them from the fourth tier): the nearest one in range lobs a shell at
///    the giant every few seconds. A shell is a slow box. It bonks, shakes the camera, shoves the
///    giant a step and knocks one rider off (see <see cref="GiantRiders.Knock"/>). Flatten the tank.
///  - HELICOPTERS, made of boxes: a news one from the third tier and army ones after, circling at
///    the giant's head height where the weapon can reach them. The army ones take pot shots at the
///    riders too. Swat one and it spins off, comes down and scores (the crew bail out first).
///
/// <see cref="RampageBootstrap"/> puts it on the Rampage object.
/// </summary>
[Title( "Giant Foes" ), Category( "Rampage" ), Icon( "flight" )]
public sealed class GiantFoes : Component
{
	public static GiantFoes Current { get; private set; }
	/// <summary>Helicopters in the air right now.</summary>
	public static int ChoppersUp => Current.IsValid() ? Current._up : 0;

	[Property, Group( "Tanks" )] public int TanksFromTier { get; set; } = 3;
	[Property, Group( "Tanks" )] public float TankRange { get; set; } = 4200f;
	[Property, Group( "Tanks" )] public float TankEvery { get; set; } = 6.5f;
	[Property, Group( "Tanks" )] public float ShellSeconds { get; set; } = 0.9f;
	/// <summary>How far a shell shoves the giant, in inches a second.</summary>
	[Property, Group( "Tanks" )] public float ShellShove { get; set; } = 260f;

	[Property, Group( "Helicopters" )] public int ChoppersFromTier { get; set; } = 2;
	[Property, Group( "Helicopters" )] public int MaxChoppers { get; set; } = 3;
	[Property, Group( "Helicopters" )] public float ChopperHealth { get; set; } = 320f;
	[Property, Group( "Helicopters" )] public float ChopperPoints { get; set; } = 350f;
	/// <summary>How far out they circle, in the giant's own heights, and how long one stays away after being swatted.</summary>
	[Property, Group( "Helicopters" )] public float OrbitHeights { get; set; } = 2.6f;
	[Property, Group( "Helicopters" )] public float ComeBackSeconds { get; set; } = 22f;
	/// <summary>Seconds between an army helicopter's shots at the riders.</summary>
	[Property, Group( "Helicopters" )] public float ChopperShotEvery { get; set; } = 13f;

	/// <summary>A helicopter: a few boxes, one of them going round. It can be hit like anything else in town.</summary>
	sealed class Chopper : IRampageTarget
	{
		public GameObject Object, Rotor;
		public bool Army, Up, Falling;
		public float Health, Angle, Bob, ReturnAt, NextShot;
		public Vector3 Position, Velocity;
		public float Spin;

		public bool Alive => Up && !Falling;
		public Vector3 Centre => Position;
		public float Radius => 120f;
		public float Hurt;
		public Vector3 Knock;

		// The blow is only noted here; GiantFoes deals with it in its own update.
		public void Hit( Vector3 velocity, float damage, Vector3 at )
		{
			if ( !Alive ) return;
			Hurt += MathF.Max( damage, 0f ) + velocity.Length * 0.02f;
			Knock = velocity;
		}
	}

	readonly List<Chopper> _choppers = new();
	GameObject _root, _shell;
	int _up;

	// The shell in flight (one at a time).
	bool _shellFlying;
	Vector3 _shellFrom;
	float _shellT;
	float _nextTank;

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
	}

	protected override void OnDisabled() => Scrap();

	protected override void OnDestroy()
	{
		Scrap();
		if ( Current == this ) Current = null;
	}

	void Scrap()
	{
		for ( int i = 0; i < _choppers.Count; i++ ) Rampage.Unregister( _choppers[i] );
		_choppers.Clear();
		if ( _root.IsValid() ) _root.Destroy();
		_root = null;
		_shell = null;
		_shellFlying = false;
		_up = 0;
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
		var player = Rampage.Player;
		if ( !Rampage.Running || !Rampage.Started || !player.IsValid() ) return;
		// Lost to a hotload: made again from nothing.
		if ( _choppers.Count > 0 && !_root.IsValid() ) Scrap();

		float dt = MathF.Min( Time.Delta, 0.05f );
		if ( dt <= 0f ) return;
		float now = Time.Now;
		float size = MathF.Max( RampageGiant.ScaleNow, 1f );
		float tall = size * 48f;
		var chest = player.WorldPosition + Vector3.Up * (tall * 0.7f);

		Tanks( player, chest, now, dt );
		Choppers( player, chest, tall, now, dt );
	}

	GameObject Root()
	{
		if ( _root.IsValid() ) return _root;
		_root = new GameObject( true, "Giant Foes" );
		_root.Flags |= GameObjectFlags.NotSaved;
		return _root;
	}

	// ---- Tanks -------------------------------------------------------------------------------------

	void Tanks( ReptileController player, Vector3 chest, float now, float dt )
	{
		if ( _shellFlying )
		{
			_shellT += dt / MathF.Max( ShellSeconds, 0.1f );
			float t = Math.Clamp( _shellT, 0f, 1f );
			var at = Vector3.Lerp( _shellFrom, chest, t ) + Vector3.Up * (MathF.Sin( t * MathF.PI ) * 260f);
			if ( _shell.IsValid() )
			{
				_shell.WorldPosition = at;
				_shell.WorldRotation = Rotation.From( now * 400f, now * 230f, 0f );
			}
			if ( t >= 1f ) Bonk( player, chest, _shellFrom );
			return;
		}

		if ( Rampage.Tier < TanksFromTier || now < _nextTank ) return;
		_nextTank = now + TankEvery;

		// The nearest tank still standing where it was parked.
		var world = RampageWorld.Current;
		if ( !world.IsValid() ) return;
		var tankKind = world.Props.Tank;
		var targets = Rampage.Targets;
		Destructible nearest = null;
		float best = TankRange * TankRange;
		for ( int i = 0; i < targets.Count; i++ )
		{
			if ( targets[i] is not Destructible prop || prop.Kind != tankKind || !prop.IsValid() || !prop.Alive || prop.Loose ) continue;
			float d = (prop.WorldPosition - chest).WithZ( 0f ).LengthSquared;
			if ( d < best ) { best = d; nearest = prop; }
		}
		if ( nearest is null ) return;

		_shellFrom = nearest.WorldPosition + Vector3.Up * 80f;
		_shellT = 0f;
		_shellFlying = true;
		if ( !_shell.IsValid() ) _shell = PopulaceFx.Block( Root(), "Shell", _shellFrom, new Vector3( 46f, 22f, 22f ), Tone.Dark );
		_shell.Enabled = true;
		world.Fx?.Burst( _shellFrom, 6, Tone.Smoke, 300f, 30f, 90f, 0.8f );
		Rampage.PlaySound( "tank_fire", _shellFrom );
	}

	/// <summary>A shell (or a helicopter's shot) has arrived: no harm done, but everybody felt it and somebody fell off.</summary>
	void Bonk( ReptileController player, Vector3 at, Vector3 from )
	{
		_shellFlying = false;
		if ( _shell.IsValid() ) _shell.Enabled = false;

		var away = (at - from).WithZ( 0f );
		Rampage.Shake( 0.6f );
		player.Kick( Vector3.Random * 14f );
		if ( away.Length > 1f ) player.Lunge( away.Normal, ShellShove );
		RampageWorld.Current?.Fx?.Burst( at, 8, Tone.Smoke, 420f, 40f, 120f, 0.9f );
		Rampage.PlaySound( "shell_bonk", at );
		var riders = GiantRiders.Current;
		if ( riders.IsValid() ) riders.Knock( from );
	}

	// ---- Helicopters -------------------------------------------------------------------------------

	void Choppers( ReptileController player, Vector3 chest, float tall, float now, float dt )
	{
		int wanted = Rampage.Tier < ChoppersFromTier ? 0 : Math.Min( 1 + (Rampage.Tier - ChoppersFromTier) / 2, Math.Max( MaxChoppers, 0 ) );
		while ( _choppers.Count < wanted ) _choppers.Add( Make( _choppers.Count > 0, _choppers.Count, now ) );

		int up = 0;
		var head = player.WorldPosition + Vector3.Up * (tall * 1.05f);
		float orbit = tall * OrbitHeights;
		for ( int i = 0; i < _choppers.Count; i++ )
		{
			var c = _choppers[i];
			if ( !c.Object.IsValid() ) continue;

			if ( c.Falling )
			{
				// Swatted: it spins away and comes down.
				c.Velocity += Vector3.Down * (700f * dt);
				c.Position += c.Velocity * dt;
				c.Spin += 900f * dt;
				c.Object.WorldPosition = c.Position;
				c.Object.WorldRotation = Rotation.From( c.Spin * 0.3f, c.Spin, c.Spin * 0.2f );
				float ground = RampageWorld.GroundHeightAt( c.Position );
				bool gone = MathF.Abs( c.Position.x ) > RampageWorld.HalfSize + 2000f || MathF.Abs( c.Position.y ) > RampageWorld.HalfSize + 2000f;
				if ( c.Position.z <= ground + 40f || gone ) Crash( c, now, gone );
				continue;
			}

			if ( !c.Up )
			{
				if ( now < c.ReturnAt ) continue;
				// It comes in from a long way off.
				c.Up = true;
				c.Health = ChopperHealth * (c.Army ? 1.5f : 1f) * Rampage.Might;
				c.Hurt = 0f;
				c.Position = head + Rotation.FromYaw( c.Angle ).Forward * (orbit * 4f) + Vector3.Up * 600f;
				c.Object.Enabled = true;
				c.NextShot = now + ChopperShotEvery * 0.6f;
				Rampage.Register( c, true );
			}
			up++;

			// What the weapon did to it since the last frame.
			if ( c.Hurt > 0f )
			{
				c.Health -= c.Hurt;
				c.Hurt = 0f;
				if ( c.Health <= 0f )
				{
					c.Falling = true;
					c.Velocity = (c.Knock * 0.8f).ClampLength( 3200f ) + Vector3.Up * 300f;
					Rampage.Unregister( c );
					Rampage.PlaySound( "chopper_hit", c.Position );
					continue;
				}
				c.Position += c.Knock.ClampLength( 600f ) * 0.15f;     // a glancing blow: it lurches
				Rampage.PlaySound( "chopper_hit", c.Position );
			}

			// Round the giant's head, bobbing, nose in.
			c.Angle += (c.Army ? 26f : 18f) * dt * (i % 2 == 0 ? 1f : -1f);
			c.Bob += dt;
			var want = head + Rotation.FromYaw( c.Angle ).Forward * (orbit * (c.Army ? 1f : 0.8f)) + Vector3.Up * (MathF.Sin( c.Bob * 1.3f + i ) * tall * 0.12f);
			c.Position += (want - c.Position) * MathF.Min( dt * 1.4f, 1f );
			c.Object.WorldPosition = c.Position;
			var facing = (head - c.Position).WithZ( 0f );
			if ( facing.Length > 1f ) c.Object.WorldRotation = Rotation.LookAt( facing.Normal ) * Rotation.FromPitch( 8f );
			if ( c.Rotor.IsValid() ) c.Rotor.LocalRotation = Rotation.FromYaw( now * 1400f );

			// The army ones take pot shots at whoever is riding.
			if ( c.Army && now >= c.NextShot && !_shellFlying && (c.Position - head).Length < orbit * 1.6f )
			{
				c.NextShot = now + ChopperShotEvery;
				_shellFrom = c.Position;
				_shellT = 0.35f;
				_shellFlying = true;
				if ( !_shell.IsValid() ) _shell = PopulaceFx.Block( Root(), "Shell", _shellFrom, new Vector3( 46f, 22f, 22f ), Tone.Dark );
				_shell.Enabled = true;
				Rampage.PlaySound( "chopper_shot", c.Position );
			}
		}
		_up = up;
	}

	/// <summary>A helicopter out of boxes: body, glass, tail boom, rotor.</summary>
	Chopper Make( bool army, int index, float now )
	{
		var c = new Chopper { Army = army, Angle = index * 137f, ReturnAt = now + 2f + index * 6f };
		var body = army ? Tone.Army : Tone.White;
		c.Object = new GameObject( Root(), true, army ? "Army Helicopter" : "News Helicopter" );
		c.Object.Flags |= GameObjectFlags.NotSaved;
		PopulaceFx.Block( c.Object, "Body", new Vector3( 0f, 0f, 0f ), new Vector3( 150f, 70f, 70f ), body );
		PopulaceFx.Block( c.Object, "Glass", new Vector3( 62f, 0f, 6f ), new Vector3( 46f, 60f, 46f ), Tone.Glass );
		PopulaceFx.Block( c.Object, "Boom", new Vector3( -120f, 0f, 12f ), new Vector3( 130f, 16f, 16f ), body );
		PopulaceFx.Block( c.Object, "Fin", new Vector3( -180f, 0f, 30f ), new Vector3( 12f, 6f, 54f ), army ? Tone.Dark : Tone.Red );
		PopulaceFx.Block( c.Object, "Stripe", new Vector3( 0f, 0f, -8f ), new Vector3( 152f, 72f, 14f ), army ? Tone.Dark : Tone.Red );
		c.Rotor = PopulaceFx.Block( c.Object, "Rotor", new Vector3( 0f, 0f, 44f ), new Vector3( 330f, 14f, 4f ), Tone.Dark );
		c.Object.Enabled = false;
		return c;
	}

	/// <summary>Down: a fireball, a shockwave, the score, and it stays away for a while.</summary>
	void Crash( Chopper c, float now, bool gone )
	{
		c.Falling = false;
		c.Up = false;
		c.ReturnAt = now + ComeBackSeconds;
		if ( c.Object.IsValid() ) c.Object.Enabled = false;

		var at = c.Position.WithZ( RampageWorld.GroundHeightAt( c.Position ) );
		Rampage.Score( at, ChopperPoints * (c.Army ? 1.5f : 1f), c.Army ? "ARMY HELICOPTER (CREW BAILED OUT)" : "NEWS HELICOPTER (STILL BROADCASTING)" );
		if ( gone ) return;
		var world = RampageWorld.Current;
		if ( world.IsValid() ) world.Boom( at, 0.02f, 700f, 1000f );
	}
}