A component that moves an entity toward a target world position. It exposes properties ToTranslate and Speed, updates WorldPosition each fixed update using Vector3.Lerp while in a Moving state, snaps to the target when within 0.1 units, and draws a gizmo arrow to the target when selected in editor.
using Sandbox;
[Category( "Functional" )]
[Icon( "double_arrow" )]
public sealed class FuncTranslate : Component
{
enum TranslateState
{
None = 0,
Moving = 1
}
[Property]
Vector3 ToTranslate { get; set; }
[Property]
float Speed { get; set; } = 1F;
[Property, Group( "Debug" ), ReadOnly]
TranslateState State { get; set; } = TranslateState.None;
protected override void OnFixedUpdate()
{
if ( State == TranslateState.Moving )
WorldPosition = Vector3.Lerp( WorldPosition, ToTranslate, Time.Delta * Speed );
if ( WorldPosition.AlmostEqual( ToTranslate, 0.1f ) )
{
WorldPosition = ToTranslate;
State = TranslateState.None;
}
base.OnFixedUpdate();
}
protected override void DrawGizmos()
{
Gizmo.Draw.Color = new Color( 135, 230, 189, 0.25f );
if ( !Gizmo.IsSelected )
return;
Gizmo.Draw.Arrow( Vector3.Zero, WorldTransform.PointToLocal( ToTranslate ), 6, 2 );
base.DrawGizmos();
}
public void StartTranslate()
{
State = TranslateState.Moving;
}
}