using System.Collections.Generic;
using Oxide.Core;
using Rust;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("DamageIndicator", "YourName", "1.0.0")]
[Description("Displays damage indicators when hitting entities")]
class DamageIndicator : RustPlugin
{
private const float DAMAGE_INDICATOR_DURATION = 1.5f;
private const float MIN_SIZE = 20f;
private const float MAX_SIZE = 100f;
private Dictionary<BasePlayer, float> lastHitTime = new Dictionary<BasePlayer, float>();
private Dictionary<string, CuiElementContainer> elementPools = new Dictionary<string, CuiElementContainer>();
private void Init()
{
Subscribe(nameof(OnEntityTakeDamage));
}
private void OnEntityTakeDamage(BaseCombatEntity entity, HitInfo hitInfo)
{
BasePlayer player = hitInfo.InitiatorPlayer;
if (player != null)
{
float timeSinceLastHit;
if (lastHitTime.TryGetValue(player, out timeSinceLastHit))
{
if (Time.time - timeSinceLastHit < DAMAGE_INDICATOR_DURATION)
{
return;
}
}
lastHitTime[player] = Time.time;
Vector3 direction = (entity.transform.position - player.eyes.position).normalized;
Vector3 screenPosition = Camera.main.WorldToScreenPoint(entity.transform.position + (direction * 2f));
if (screenPosition.z > 0f)
{
float distance = Vector3.Distance(entity.transform.position, player.transform.position);
float damage = Mathf.Clamp(hitInfo.damageTypes.Total(), 0f, entity.MaxHealth());
float damagePercentage = damage / entity.MaxHealth();
Color color = Color.Lerp(Color.green, Color.red, damagePercentage);
float size = Mathf.Clamp(1500f / distance, MIN_SIZE, MAX_SIZE);
CuiElementContainer container = GetElementContainer(entity.GetInstanceID().ToString());
container.Add(GetLabelElement(damage.ToString(), size));
container.Add(GetPanelElement(color));
CuiHelper.AddUi(player, container, entity.GetInstanceID().ToString());
}
timer.Once(DAMAGE_INDICATOR_DURATION, () =>
{
CuiElementContainer container = RemoveElementContainer(entity.GetInstanceID().ToString());
CuiHelper.DestroyUi(player, container, entity.GetInstanceID().ToString());
});
}
}
private CuiLabel GetLabelElement(string text, float size)
{
return new CuiLabel
{
Text = { Text = text, FontSize = size.ToString(), Align = TextAnchor.MiddleCenter, Color = Color.white.ToHex() },
RectTransform = { AnchorMin = "0 0", AnchorMax = "1 1" }
};
}
private CuiPanel GetPanelElement(Color color)
{
return new CuiPanel
{
Image = { Color = color.ToHex() },
RectTransform = { AnchorMin = "0 0", AnchorMax = "1 1" }
};
}
private CuiElementContainer GetElementContainer(string key)
{
if (!elementPools.ContainsKey(key))
{
elementPools[key] = new CuiElementContainer();
}
return elementPools[key];
}
private CuiElementContainer RemoveElementContainer(string key)
{
CuiElementContainer container = elementPools[key];
elementPools.Remove(key);
return container;
}
}
}