A game component representing a falling object. It tracks spawn time, lifetime and fall progress, moves the object downward over time from a fixed starting height, and destroys the GameObject when it hits the ground.
using System;
using Sandbox;
public class FallingObject : Component
{
public Player Shooter { get; set; }
public TimeSince TimeSinceSpawn { get; set; }
public float Lifetime { get; set; }
public float FallProgress { get; set; }
protected float _startingHeight = 1024f;
public bool HasHitGround { get; set; }
protected override void OnStart()
{
base.OnStart();
TimeSinceSpawn = 0f;
if ( IsProxy )
return;
}
protected override void OnUpdate()
{
base.OnUpdate();
if ( IsProxy )
return;
if ( TimeSinceSpawn > Lifetime )
{
if( !HasHitGround )
HitGround();
}
else
{
FallProgress = Utils.Map( TimeSinceSpawn, 0f, Lifetime, 0f, 1f );
WorldPosition = new Vector3( WorldPosition.x, WorldPosition.y, Utils.Map( FallProgress, 0f, 1f, _startingHeight, 0f ) );
}
}
public virtual void HitGround()
{
GameObject.Destroy();
}
}