A component that listens for physics collisions and triggers a death sequence for the player henrietta. It gets Rigidbody and renderer references, checks collision tags, plays a death sound and particle emitter, hides the visible model, zeros velocity, deducts score, and reloads the current scene after a delay.
using Sandbox;
using static Sandbox.Sprite;
using static System.Runtime.CompilerServices.RuntimeHelpers;
public sealed class CollisionHandler : Component, Component.ICollisionListener, Component.ITriggerListener
{
[Property] public SkinnedModelRenderer model { get; set; }
[Property] public Rigidbody rb { get; set; }
[Property] int levelLoadDelay = 2000;
[Property] public SoundEvent death { get; set; }
[Property] public GameObject visibleVar;
[Property] static Scene ActiveScene { get; set; }
[Property] public string[] Tags { get; set; } = { "friendly","finish" };
[Property] public ParticleSphereEmitter Feathers { get; set; }
[Property] public ChickenControls chicken { get; set; }
void Start()
{
rb = Components.Get<Rigidbody>();
visibleVar = Scene.Directory.FindByName( "/Player/henrietta" ).FirstOrDefault();
model = GetComponent<SkinnedModelRenderer>();
}
void Update()
{
}
void ICollisionListener.OnCollisionStart(Collision collision)
{
var otherBody = collision.Other;
var hitGameObject = otherBody.GameObject;
chicken.chickenVel = hitGameObject.Components.Get<AnimatedVelocityComponent>();
if (collision.Other.GameObject.Tags.Has("friendly"))
{
}
else
{
StartDeathSequence();
}
}
void ICollisionListener.OnCollisionStop(CollisionStop collision)
{
}
void ICollisionListener.OnCollisionUpdate(Collision collision)
{
}
public void StartDeathSequence()
{
//add Death Animation/Sfx/Vfx
GameObject.StopAllSounds();
GameObject.PlaySound( death );
Feathers.Enabled = true;
rb.Velocity = Vector3.Zero;
visibleVar.Enabled = false;
ReloadLevel();
ScoreManager.CurrentScore -= 1000;
if ( ScoreManager.CurrentScore < 0 )
{
ScoreManager.CurrentScore = 0;
}
}
async void DelayedMethod()
{
var myScript = GameObject.Components.Get<ChickenControls>();
myScript.Enabled = false;
// Wait for 2 seconds
await Task.Delay( levelLoadDelay );
// Code to run after delay
GameObject.StopAllSounds();
Game.ActiveScene.Load( Game.ActiveScene.Source );
}
void ReloadLevel()
{
DelayedMethod();
}
}