// Event structure containing information used to apply damage to an object. class Health : ZilchComponent { // The max health we can have [Property] var MaxHealth : Real = 50.0; // How much health we currently have. Separated from MaxHealth so that we can clamp to max health. var CurrentHealth : Real = 50.0; // If we reach zero health should we call destroy on ourself? [Property] var DestroyAtZeroHealth : Boolean = true; [Property] var Timer : Real = 0.0; // A scalar to modify how much damage this object takes. [Property] var DamageScalar : Real = 1.0; // When we die, we sound out a death event. sends Death : ZilchEvent; function Initialize(init : CogInitializer) { this.CurrentHealth = this.MaxHealth; Zero.Connect(this.Owner, Events.ApplyDamage, this.OnApplyDamage); Zero.Connect(this.Space, Events.LogicUpdate, this.OnLogicUpdate); } function OnLogicUpdate(event : UpdateEvent) { this.Timer += event.Dt; } function OnApplyDamage(damageEvent : DamageEvent) { this.ApplyDamage(damageEvent.Damage); } function ApplyDamage(damage : Real) { // Compute the total damage based upon our damage scalar. damage = damage * this.DamageScalar; if(this.Timer >= 1.0) { this.CurrentHealth -= damage; this.Timer = 0.0; } // Clamp our current health (in my case I don't want to have // to heal through negative health so I clamp to 0). this.CurrentHealth = Math.Clamp(this.CurrentHealth, 0.0, this.MaxHealth); // If we have no health. if(this.CurrentHealth <= 0.0) { // Let anyone listening know we just died. var toSend = ZilchEvent(); this.Owner.DispatchEvent(Events.Death, toSend); // And if the property is set destroy ourself. if(this.DestroyAtZeroHealth) { this.Owner.Destroy(); } } } }