Something like ...
using System;
using System.Collections.Generic;
using System.Linq;
using Sandbox.Citizen;
// The citizen model still runs on the old animgraph, which the engine marks obsolete.
#pragma warning disable CS0618
/// <summary>
/// The owners' envoy. Walks across the cave floor to the lizard, stops and makes its offer, and
/// can be killed. The cave keeps its collision at the breach, so it is moved by script: a step
/// toward the player each frame, then a downward trace to stay on the ground.
/// </summary>
[Title( "Envoy" ), Category( "Story" ), Icon( "record_voice_over" )]
public sealed class Envoy : Component
{
[Property] public float WalkSpeed { get; set; } = 90f;
/// <summary>How far from the player it stops to talk, in inches (measured along the ground).</summary>
[Property] public float StopDistance { get; set; } = 230f;
/// <summary>Seconds each line of the offer stays up.</summary>
[Property] public float LineSeconds { get; set; } = 4.5f;
/// <summary>The offer, shown one line at a time while the player stays near.</summary>
[Property] public List<string> OfferLines { get; set; } = new()
{
"Good evening. We are the Owners. We own this rock now. We own most rocks. It is nothing personal.",
"Work with us and you shall want for nothing. Resources. Servants. A tasteful robe with a hood.",
"And food. More than you have ever seen in here. Canapes. You do not know what a canape is. You will.",
"All we ask in return is everything, for ever. There is a form. Initial here, here and on the eye.",
};
/// <summary>Said instead of the offer when the player looks like one of the owners.</summary>
[Property] public string ColleagueLine { get; set; } = "Ah, a colleague. Have you seen the creature that lives in here? Small. Naked. Dreadful posture.";
/// <summary>How long the fall takes when it is killed.</summary>
[Property] public float FallSeconds { get; set; } = 0.4f;
/// <summary>Distance walked between boot sounds, in inches.</summary>
[Property] public float StrideLength { get; set; } = 38f;
[Property] public string BootsSound { get; set; } = "sounds/opening/boots.sound";
/// <summary>The distorted voice, played at its head with every line it says.</summary>
[Property] public string VoiceSound { get; set; } = "sounds/opening/voice_garble.sound";
public bool IsDead { get; private set; }
/// <summary>True while it is walking. The escorts read this to keep formation.</summary>
public bool IsMoving { get; private set; }
/// <summary>True while it is standing in front of the player, talking.</summary>
public bool IsTalking { get; private set; }
const string SpeakerName = "ENVOY";
Health _health;
SkinnedModelRenderer _renderer;
CitizenAnimationHelper _anim;
GameObject _player;
int _line;
float _sinceStride; // inches walked since the last boot sound
TimeSince _sinceLine;
TimeSince _sinceDeath;
Rotation _deathFrom;
Rotation _deathTo;
protected override void OnStart()
{
_health = Components.Get<Health>();
_renderer = Components.Get<SkinnedModelRenderer>( FindMode.EverythingInSelfAndDescendants );
_anim = Components.Get<CitizenAnimationHelper>( FindMode.EverythingInSelfAndDescendants );
if ( _health is not null ) _health.Killed += OnKilled;
}
protected override void OnDestroy()
{
if ( _health is not null ) _health.Killed -= OnKilled;
}
void OnKilled( GameObject attacker )
{
if ( IsDead ) return;
IsDead = true;
IsMoving = false;
StopTalking();
Animate( Vector3.Zero );
// Fall onto its back: a quarter turn about its own sideways axis.
_sinceDeath = 0f;
_deathFrom = WorldRotation;
_deathTo = Rotation.FromAxis( WorldRotation.Right, 90f ) * WorldRotation;
}
protected override void OnUpdate()
{
if ( Scene.IsEditor ) return;
if ( IsDead )
{
float t = FallSeconds <= 0f ? 1f : MathF.Min( _sinceDeath / FallSeconds, 1f );
WorldRotation = Rotation.Slerp( _deathFrom, _deathTo, t * t ); // speeds up as it tips
return;
}
if ( !_player.IsValid() )
_player = Scene.GetAllComponents<ReptileController>().FirstOrDefault()?.GameObject;
if ( !_player.IsValid() )
{
IsMoving = false;
Animate( Vector3.Zero );
return;
}
// Only the distance along the ground counts, so it also stops under a lizard on the ceiling.
var toPlayer = (_player.WorldPosition - WorldPosition).WithZ( 0 );
float distance = toPlayer.Length;
var direction = distance > 0.01f ? toPlayer / distance : WorldRotation.Forward.WithZ( 0 ).Normal;
// Once stopped, the player has to back off a little before it starts walking again.
float stopAt = IsTalking ? StopDistance * 1.25f : StopDistance;
var velocity = Vector3.Zero;
if ( distance > stopAt )
{
StopTalking();
velocity = direction * WalkSpeed;
WorldPosition = SnapToGround( WorldPosition + velocity * Time.Delta );
_sinceStride += WalkSpeed * Time.Delta;
if ( _sinceStride >= StrideLength )
{
_sinceStride = 0f;
StorySound.Play( BootsSound, WorldPosition );
}
}
else
{
Talk();
}
IsMoving = velocity.Length > 1f;
// Walking and talking both face the player; turn smoothly rather than snapping.
var facing = Rotation.LookAt( direction, Vector3.Up );
WorldRotation = Rotation.Slerp( WorldRotation, facing, MathF.Min( Time.Delta * 8f, 1f ) );
Animate( velocity );
}
/// <summary>Puts a position on the ground below (or just above) it, if there is any.</summary>
Vector3 SnapToGround( Vector3 position )
{
var trace = Scene.Trace.Ray( position + Vector3.Up * 50f, position + Vector3.Down * 150f )
.IgnoreGameObjectHierarchy( GameObject );
if ( _player.IsValid() ) trace = trace.IgnoreGameObjectHierarchy( _player );
var tr = trace.Run();
if ( !tr.Hit ) return position;
// People don't walk up boulders: if the ground ahead is a big step up, sidle round it.
if ( tr.HitPosition.z - WorldPosition.z <= 24f ) return tr.HitPosition;
var ahead = (position - WorldPosition).WithZ( 0 );
var side = WorldPosition + new Vector3( -ahead.y, ahead.x, 0 ) * _sidestep;
var sideTrace = Scene.Trace.Ray( side + Vector3.Up * 50f, side + Vector3.Down * 150f )
.IgnoreGameObjectHierarchy( GameObject );
if ( _player.IsValid() ) sideTrace = sideTrace.IgnoreGameObjectHierarchy( _player );
var sideHit = sideTrace.Run();
if ( sideHit.Hit && sideHit.HitPosition.z - WorldPosition.z <= 24f ) return sideHit.HitPosition;
_sidestep = -_sidestep; // blocked that way too: try the other side next step
return WorldPosition;
}
float _sidestep = 1f;
void Talk()
{
var director = StoryDirector.Get( Scene );
if ( director is null ) return;
if ( !IsTalking )
{
IsTalking = true;
_line = 0;
_sinceLine = LineSeconds; // say the first line straight away
}
if ( _sinceLine < LineSeconds ) return;
_sinceLine = 0f;
// A lizard wearing an owner's skin is taken for one of them.
if ( FactionTag.Of( _player ) == FactionTag.Owners )
{
director.ShowMessage( ColleagueLine, LineSeconds + 0.5f, SpeakerName );
Speak();
return;
}
if ( OfferLines is null || OfferLines.Count == 0 ) return;
// The offer is made once. After that it waits, and now and then lets you know it.
if ( _line < OfferLines.Count )
{
director.ShowMessage( OfferLines[_line], LineSeconds + 0.5f, SpeakerName );
_line++;
Speak();
return;
}
if ( _sinceOffer < WaitingSeconds && _line > OfferLines.Count ) return;
if ( _line == OfferLines.Count ) { _line++; _sinceOffer = 0f; return; } // a silence first
_sinceOffer = 0f;
if ( WaitingLines is null || WaitingLines.Count == 0 ) return;
director.ShowMessage( WaitingLines[_waiting++ % WaitingLines.Count], LineSeconds, SpeakerName );
Speak();
}
/// <summary>Said now and then after the offer, while it waits for an answer.</summary>
[Property] public List<string> WaitingLines { get; set; } = new()
{
"Well?",
"We know you understand us. We own several universities.",
"It is a generous offer. It will not be made twice. The pen is on loan.",
};
/// <summary>Seconds of silence between waiting lines.</summary>
[Property] public float WaitingSeconds { get; set; } = 11f;
TimeSince _sinceOffer;
int _waiting;
/// <summary>The garbled voice that goes with a line, from about where its head is.</summary>
void Speak() => StorySound.Play( VoiceSound, WorldPosition + Vector3.Up * 64f );
void StopTalking()
{
if ( !IsTalking ) return;
IsTalking = false;
// Only take down the message if it is still ours.
var director = StoryDirector.Get( Scene );
if ( director is not null && director.Speaker == SpeakerName ) director.ClearMessage();
}
/// <summary>Walk or idle on the citizen animgraph. Does nothing for other models.</summary>
void Animate( Vector3 velocity )
{
if ( _anim.IsValid() )
{
_anim.WithVelocity( velocity );
_anim.WithWishVelocity( velocity );
_anim.IsGrounded = true;
return;
}
if ( !_renderer.IsValid() ) return;
// No helper: set the few citizen parameters that matter. Unknown names are ignored.
float forward = Vector3.Dot( velocity, WorldRotation.Forward );
float left = Vector3.Dot( velocity, WorldRotation.Left );
_renderer.Set( "b_grounded", true );
_renderer.Set( "move_groundspeed", velocity.Length );
_renderer.Set( "wish_groundspeed", velocity.Length );
_renderer.Set( "move_x", forward );
_renderer.Set( "move_y", left );
_renderer.Set( "wish_x", forward );
_renderer.Set( "wish_y", left );
}
}