A game component that acts as a bouncing shield trigger. When another object enters its trigger it computes a push direction away from the shield, applies a velocity impulse to a CharacterController or Rigidbody if present, plays a bounce sound, and triggers a camera shake.
using Sandbox;
public sealed class BouncyShield : Component, Component.ITriggerListener
{
[Property] public float BounceForce { get; set; } = 1500f;
[Property] public SoundEvent BounceSound { get; set; }
public void OnTriggerEnter( Collider other )
{
var rootObj = other.GameObject.Root;
var pushDir = (rootObj.WorldPosition - WorldPosition).Normal;
pushDir.z = 0.3f;
bool bounced = false;
var cc = rootObj.Components.Get<CharacterController>();
if ( cc.IsValid() )
{
cc.Velocity = pushDir * BounceForce;
bounced = true;
}
var rb = rootObj.Components.Get<Rigidbody>();
if ( rb.IsValid() )
{
rb.Velocity = pushDir * BounceForce;
bounced = true;
}
if ( bounced )
{
if ( BounceSound != null )
{
Sound.Play( BounceSound, WorldPosition );
}
CameraJuice.Instance?.Shake( 12f );
}
}
}