RacesOfValheim/JotunnModStub/Sverm/SvermRavagerForm.cs
2026-08-19 19:18:24 +02:00

718 lines
34 KiB
C#

using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Ravager Strain: from Yagluth on, a Sverm can become a Seeker Brute for two minutes.
///
/// Replaces the earlier Stinger Morph (a Deathsquito flight form). Players found that form's
/// glass-cannon shape too strong for what it cost, so this is the opposite trade: no flight,
/// no summons, and the carapace is worth twice as much for as long as the form holds - the
/// carapace itself is never removed. Same duration, same cooldown as the form it replaces;
/// only the shape of the trade changed.
///
/// COMBAT FOLLOWS FENRIR AND SKADI'S OWN PATTERN, not Valheim's weapon system. Nothing gets
/// equipped. Humanoid.StartAttack is blocked outright for as long as the form is up, and
/// RavagerFormBehavior runs its own attack coroutines instead - a trigger on the model's
/// Animator, a timed Physics.OverlapSphere, real damage numbers borrowed from
/// SvermRavagerAttacks. The earlier version tried to clone the Brute's own weapons and let
/// them run through Valheim's real Attack.Start, and it never stopped fighting the game:
/// GetCurrentBlocker turning right-click into a parry, player.InAttack() ending before the
/// visible clip did, wiring a working secondary attack by hand. Left click bites, right click
/// rams, middle click slams, G roars - a short-cooldown AoE around the player rather than a
/// fourth forward swing, since the Brute's own taunt was never a hit in the first place.
/// </summary>
public static class SvermRavagerForm
{
public static bool IsActive { get; private set; }
private static GameObject model;
private static float expiresAt;
private static float nextAllowedAt;
// Guards the ~1.1s "gpower" gesture in EnterRoutine, and separately the shrink in
// ExitRoutine: without them, a second key press mid-gesture would start a second routine
// on top of the first, the same double-transform bug Aswid's own isTransformingSequence
// flag exists to prevent.
private static bool transforming;
private static bool exiting;
private static GameObject template;
private static bool templateBuildAttempted;
// ─── The template ───────────────────────────────────────────────────
/// <summary>
/// Strips the Seeker Brute's borrowed model down to a costume, once, from a moment where
/// that is safe to do - the same rule ModelBorrow exists to enforce, and the same one
/// WarVultureVisual.BuildTemplate follows for its own borrowed bird. Call it from a
/// CreateAllModAssets-time hook; it no-ops on every call after the first.
///
/// FOUND IN PLAY: the old code instantiated the source's Animator sub-object directly at
/// Enter() time, mid-gameplay, and never stripped it. The Brute's own footstep-effect
/// script came along for the ride, alive, and spent every frame of the form logging
/// "FAiled to find foot:l.backfoot" because the bones it wanted only exist on the
/// source's own untouched rig - along with whatever else survived (Character, MonsterAI,
/// a Rigidbody, a ZNetView) that this class never meant to carry.
///
/// DestroyImmediate only, and only because the holder is inactive before the Instantiate
/// below: an active clone would Awake every one of those scripts for a frame before the
/// strip could remove them, which is the exact bug ModelBorrow's own docstring names.
/// Object.Destroy (deferred) would not be safe here for the same reason - by the time it
/// actually runs, the frame that mattered has already passed.
/// </summary>
public static void BuildTemplate()
{
if (template != null || templateBuildAttempted) return;
templateBuildAttempted = true;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.RavagerCreature);
GameObject animated = source != null ? source.GetComponentInChildren<Animator>()?.gameObject : null;
if (animated == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{SvermConfig.RavagerCreature}' model to build the " +
"Ravager Strain template from; the form will run without a body.");
return;
}
GameObject holder = new GameObject("SvermRavagerTemplate");
Object.DontDestroyOnLoad(holder);
holder.SetActive(false); // BEFORE Instantiate: nothing on the copy gets to Awake.
GameObject copy = Object.Instantiate(animated, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = animated.transform.localScale;
// Everything that is not a Renderer or a Transform. Animator is a Behaviour, not a
// MonoBehaviour, so it is never touched by the first loop and survives on purpose -
// it is the one live thing this costume is allowed to keep.
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);
}
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true))
{
if (body != null) Object.DestroyImmediate(body);
}
foreach (ZNetView nview in copy.GetComponentsInChildren<ZNetView>(true))
{
if (nview != null) Object.DestroyImmediate(nview);
}
template = copy;
Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain template built from '{SvermConfig.RavagerCreature}'.");
}
// ─── Driver ──────────────────────────────────────────────────────────
public static void Tick(Player player)
{
if (player == null || player != Player.m_localPlayer)
{
return;
}
// While the entry gesture (EnterRoutine) or the exit shrink (ExitRoutine) is still
// playing, nothing below should react to a key press or a death mid-sequence.
if (transforming || exiting) return;
// Death ends it immediately, and so does ceasing to be a Sverm. Both leave a body
// hidden and a bug that is very hard to read, so they are checked before anything
// else - and neither one gets the graceful shrink, on purpose: a corpse or a race
// change is not the moment for a half-second animation, it is the moment to clean up.
if (IsActive && (player.IsDead() || !SvermVisuals.IsSvermPlayer(player)))
{
Exit(player, spendCooldown: false);
return;
}
if (IsActive && Time.time >= expiresAt)
{
RunExit(player, spendCooldown: true, "The shell recedes.");
return;
}
// No manual cancel: the form is short (two minutes) on purpose, and letting G end it
// early meant a stray press mid-fight burned the whole cooldown for a form that had
// barely started. While IsActive, the key does nothing at all - the timer is the only
// way out, same as death or losing the race.
if (IsActive) return;
if (!SvermConfigManagement.RavagerKey.Value.IsDown()) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
if (!SvermProgression.Current.RavagerForm)
{
player.Message(MessageHud.MessageType.Center, "The strain has not taken yet.");
return;
}
if (Time.time < nextAllowedAt)
{
player.Message(MessageHud.MessageType.Center, "The strain is spent.");
return;
}
if (SvermRace.Instance != null)
{
SvermRace.Instance.StartCoroutine(EnterRoutine(player));
}
else
{
// No host to run the gesture on - a state that should not happen outside a very
// early loading frame, but the form working ungestured beats it not working at
// all.
Enter(player);
}
}
/// <summary>
/// The transformation's own animation: the same "gpower" arms-raised gesture Aswid,
/// Skadi and Fenrir all borrow for their own transformations (RaceInput's own comment
/// names all three), suppressed so it never fires the player's real Guardian Power. The
/// actual state change - IsActive, the weapons, the hidden body, the worn model - waits
/// out the gesture first, the same order TransformIntoBatRoutine uses in AswidRace.cs.
/// </summary>
private static System.Collections.IEnumerator EnterRoutine(Player player)
{
transforming = true;
ZSyncAnimation zAnim = player.GetComponent<ZSyncAnimation>();
if (zAnim != null)
{
RaceInput.SuppressGuardianPowerBriefly();
zAnim.SetTrigger("gpower");
}
yield return new WaitForSeconds(1.1f);
// The gesture takes over a second; a lot can happen to the player in that window.
if (player == null || player != Player.m_localPlayer || player.IsDead() || !SvermVisuals.IsSvermPlayer(player))
{
transforming = false;
yield break;
}
Enter(player);
transforming = false;
}
// ─── Enter and leave ─────────────────────────────────────────────────
private static void Enter(Player player)
{
IsActive = true;
expiresAt = Time.time + SvermConfig.RavagerDurationSeconds;
player.GetSEMan().AddStatusEffect(SvermConfig.RavagerSE.GetStableHashCode(), true);
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Hide(visual, "sverm-ravager");
// BuildTemplate is NOT called from here. Enter() runs from Tick(), inside Update, and
// the strip needs DestroyImmediate on an inactive object - safe only from the
// CreateAllModAssets-time hook that actually builds this. If that hook never ran, the
// template stays null and the form falls back to a bare body below rather than
// risking an unsafe strip mid-gameplay.
if (template != null)
{
// A plain Instantiate of an already-stripped template - safe in this context
// (mid-gameplay, inside Update) precisely because nothing left on it can Awake
// into anything. See BuildTemplate for why that matters.
model = Object.Instantiate(template, player.transform.position, player.transform.rotation, player.transform);
model.transform.localPosition = Vector3.zero;
// SCALE COMES FROM THE SOURCE, not from 1 - same reasoning as the old Stinger
// Morph. The multiplier defaults to 1 (the Brute's own authored size, full bulk,
// by design) and is only there for an eye to correct it against.
Vector3 fullScale = template.transform.localScale * SvermConfigManagement.RavagerScale;
// Grows in rather than popping to full size at once, starting at half scale and
// reaching full over half a second - the entrance the transformation itself was
// missing. ScaleTween owns the model reference for that half second, not Enter,
// so nothing here needs to wait on it.
model.transform.localScale = fullScale * 0.5f;
if (SvermRace.Instance != null)
{
SvermRace.Instance.StartCoroutine(ScaleTween(model, fullScale * 0.5f, fullScale, 0.5f));
}
else
{
model.transform.localScale = fullScale;
}
// Which way the model faces is a thing only an eye can settle, so it is a config
// value and not a constant - same as the old form.
model.transform.localRotation = Quaternion.Euler(0f, SvermConfigManagement.RavagerYaw, 0f);
model.AddComponent<RavagerFormBehavior>();
}
else
{
// No model is survivable - the carapace and the armour buff still apply - but it
// is worth saying out loud rather than leaving someone to wonder why they turned
// into nothing.
GameObject bare = new GameObject("SvermRavagerBody");
bare.transform.SetParent(player.transform, false);
bare.AddComponent<RavagerFormBehavior>();
model = bare;
}
PlayEffect(SvermConfig.RavagerMorphInEffects, player.transform.position);
player.Message(MessageHud.MessageType.Center, "The Ravager Strain takes hold.");
}
private static void PlayEffect(string[] candidates, Vector3 where)
{
foreach (string name in candidates)
{
GameObject fx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (fx == null) continue;
Object.Instantiate(fx, where, Quaternion.identity);
return;
}
}
private static void Exit(Player player, bool spendCooldown)
{
IsActive = false;
PlayEffect(SvermConfig.RavagerMorphOutEffects, player.transform.position);
// Nothing was ever equipped for this form - see the class doc for why - so there is
// nothing to hand back here. SvermClawSlot's own throttled pass (Sverm_PlayerUpdate_Patch)
// keeps the claws maintained regardless of Ravager Strain, on its own schedule.
if (model != null)
{
// FOUND IN PLAY: Object.Destroy is deferred to the end of the frame, so
// RavagerFormBehavior's own LateUpdate - the one that re-hides the player's
// Visual every frame to kill the equipment-swap flicker - was still firing AFTER
// Show() ran a few lines below, undoing it the instant it happened. Nothing called
// Show() again afterward, so the player (and whatever VisEquipment had just
// rebuilt while unequipping the Ravager weapon above - the carapace included)
// stayed hidden for good. SetActive(false) makes Unity skip every further
// Update/LateUpdate on this GameObject for the rest of the frame even though the
// object itself is not gone yet, which is the only part of "destroyed" that
// actually matters here.
model.SetActive(false);
Object.Destroy(model);
model = null;
}
player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerSE.GetStableHashCode());
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Show(visual, "sverm-ravager-revert");
if (spendCooldown)
{
nextAllowedAt = Time.time + SvermConfig.RavagerCooldownSeconds;
player.GetSEMan().AddStatusEffect(SvermConfig.RavagerCdSE.GetStableHashCode(), true);
}
}
/// <summary>Kicks off the graceful exit (shrink, then Exit) if there is a host to run it on.</summary>
private static void RunExit(Player player, bool spendCooldown, string message)
{
if (SvermRace.Instance != null)
{
SvermRace.Instance.StartCoroutine(ExitRoutine(player, spendCooldown, message));
}
else
{
Exit(player, spendCooldown);
if (message != null) player.Message(MessageHud.MessageType.Center, message);
}
}
/// <summary>
/// The mirror of EnterRoutine's grow-in: the model shrinks to half its current scale over
/// half a second before Exit() actually tears anything down, so the form has a send-off
/// instead of a hard cut. Used for the two GRACEFUL exits only (timeout, manual toggle) -
/// death and a race change go through Exit() directly, immediately, on purpose.
/// </summary>
private static System.Collections.IEnumerator ExitRoutine(Player player, bool spendCooldown, string message)
{
exiting = true;
if (model != null)
{
Vector3 current = model.transform.localScale;
yield return ScaleTween(model, current, current * 0.5f, 0.5f);
}
Exit(player, spendCooldown);
if (message != null) player.Message(MessageHud.MessageType.Center, message);
exiting = false;
}
/// <summary>
/// Linear scale from <paramref name="from"/> to <paramref name="to"/> over
/// <paramref name="duration"/> seconds. Bails cleanly if the target disappears mid-tween
/// rather than assuming it cannot - Exit() is free to destroy the model while this is
/// still yielding.
/// </summary>
private static System.Collections.IEnumerator ScaleTween(GameObject target, Vector3 from, Vector3 to, float duration)
{
if (target == null) yield break;
float elapsed = 0f;
while (elapsed < duration)
{
if (target == null) yield break;
elapsed += Time.deltaTime;
target.transform.localScale = Vector3.Lerp(from, to, elapsed / duration);
yield return null;
}
if (target != null) target.transform.localScale = to;
}
// ─── The three attacks ───────────────────────────────────────────────
/// <summary>
/// Blocks Valheim's own attack system outright for the whole form, the same way
/// SkadiAttackPatch blocks it for the dragon forms. Whatever the player happens to have
/// equipped never swings and never deals damage while this is up; RavagerFormBehavior's
/// own coroutines are the only thing that can land a hit.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Sverm_RavagerBlockNativeAttack_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (__instance != Player.m_localPlayer) return true;
return !IsActive;
}
}
/// <summary>No food, no mead, no potions. The form is meant to be survived, not sustained.</summary>
[HarmonyPatch(typeof(Humanoid), "UseItem")]
public static class Sverm_RavagerUseItem_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (!IsActive) return true;
return !(__instance is Player player) || player != Player.m_localPlayer;
}
}
}
/// <summary>
/// Locomotion AND combat, both held on every frame while the form is up - built on the same
/// method FenrirFormBehavior and DrakeFormBehavior already use for their own transformations,
/// not on Valheim's weapon system. See SvermRavagerAttacks for why.
///
/// UNLIKE THE OLD STINGER MORPH, this never touches m_debugFly - the whole point of Ravager
/// Strain is that it stays on the ground. The player moves exactly as they always do; this
/// component only feeds the worn model's own Animator whatever standard Valheim monster
/// parameters it actually has - forward_speed and onGround, the same pair DrakeFormBehavior
/// drives - plus a jump cue IF the Brute's controller turns out to carry one, checked once at
/// Start rather than assumed. Every SetFloat/SetBool/SetTrigger is guarded by that check, the
/// same pattern WarVultureVisual.Has uses: driving a parameter name the controller does not
/// have is a silent no-op in Unity, but the guard is what makes "does it have one" an answer
/// this logs instead of a guess nobody can see.
/// </summary>
public class RavagerFormBehavior : MonoBehaviour
{
private Animator anim;
private bool hasForwardSpeed;
private bool hasOnGround;
private bool hasJumpTrigger;
private bool hasJumpBool;
private bool wasGrounded = true;
// While true, Update skips both the locomotion sync and any new attack input - the same
// gate FenrirFormBehavior's own isAttacking flag uses, and the direct answer to "the
// animation has to finish before the Brute can move": nothing here can start moving the
// model again, or start a second attack, until the coroutine below clears it.
private bool isAttacking;
// The taunt's own cooldown - short, and tracked separately from the other three, which
// have no cooldown of their own beyond their own lock duration.
private float nextTauntAt;
// Every distinct trigger name that has been checked against this Animator and found
// present, so PlayAttack does not pass a name to SetTrigger the controller cannot use.
private readonly System.Collections.Generic.HashSet<string> knownTriggers = new System.Collections.Generic.HashSet<string>();
private void Start()
{
anim = GetComponentInChildren<Animator>();
if (anim == null || anim.runtimeAnimatorController == null) return;
// The same three settings WarVultureVisual.PrepareAnimator uses on its own borrowed
// model, for the same reasons. applyRootMotion=false: the slam's clip carries real
// baked motion, and left at the default Unity would walk the COSTUME out from under
// its wearer - the model has no collider and no gameplay meaning, only the player
// does, and the player already moves through Valheim's own code, not an animation
// clip. fireEvents=false: attack clips carry animation events aimed at
// CharacterAnimEvent, which BuildTemplate already stripped off this model, so left on
// every swing would log "has no receiver" for nothing. cullingMode: keeps the model
// animating even when it is partly off the bottom of the screen, the way a body
// standing close to the camera often is.
anim.applyRootMotion = false;
anim.fireEvents = false;
anim.cullingMode = AnimatorCullingMode.AlwaysAnimate;
foreach (AnimatorControllerParameter param in anim.parameters)
{
if (param.type == AnimatorControllerParameterType.Float && param.name == "forward_speed")
hasForwardSpeed = true;
else if (param.type == AnimatorControllerParameterType.Bool && param.name == "onGround")
hasOnGround = true;
else if (param.type == AnimatorControllerParameterType.Trigger && param.name == "jump")
hasJumpTrigger = true;
else if (param.type == AnimatorControllerParameterType.Bool && param.name == "jump")
hasJumpBool = true;
else if (param.type == AnimatorControllerParameterType.Trigger)
knownTriggers.Add(param.name);
}
Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain model animator: forward_speed={hasForwardSpeed}, " +
$"onGround={hasOnGround}, jump=" +
(hasJumpTrigger ? "trigger" : hasJumpBool ? "bool" : "none") + ".");
}
/// <summary>
/// FOUND IN PLAY: the real body flickered into view on every equipment change elsewhere
/// in the game (a nearby player's gear, a tamed animal, anything that shares
/// VisEquipment's rebuild path) - PlayerVisualHider's own comment already says gear
/// changes make hidden things visible again, which is why it re-sweeps on a timer rather
/// than hiding once. That timer is 0.25s, long enough to be noticed.
///
/// LateUpdate, not Update: Unity runs every component's Update before any component's
/// LateUpdate in a given frame, so this always runs after whatever rebuilt visuals
/// earlier in the same frame, rather than racing it. Re-hiding every single frame the
/// form is up closes the gap the 0.25s timer leaves open, without touching
/// PlayerVisualHider's own interval, which every other race's hidden body still relies on.
/// </summary>
private void LateUpdate()
{
Player player = Player.m_localPlayer;
if (player == null) return;
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Hide(visual, "sverm-ravager");
}
private void Update()
{
Player player = Player.m_localPlayer;
if (player == null || player.IsDead()) return;
if (isAttacking) return;
bool grounded = player.IsOnGround();
if (hasForwardSpeed)
{
Vector3 velocity = player.GetVelocity();
velocity.y = 0f;
anim.SetFloat("forward_speed", velocity.magnitude);
}
if (hasOnGround) anim.SetBool("onGround", grounded);
if (hasJumpTrigger)
{
// The rising edge only, so a trigger fires once per jump rather than once per
// frame spent airborne.
if (!grounded && wasGrounded) anim.SetTrigger("jump");
}
else if (hasJumpBool)
{
anim.SetBool("jump", !grounded);
}
wasGrounded = grounded;
if (!RaceInput.Allowed || !grounded) return;
// Right click rams, left click bites, middle click slams. All three read raw
// UnityEngine.Input rather than going anywhere near Humanoid.StartAttack, which
// Sverm_RavagerBlockNativeAttack_Patch refuses outright for the whole form - see the
// class doc for why that turned out to be the only reliable option.
if (Input.GetMouseButtonDown(1))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f));
}
else if (Input.GetMouseButtonDown(0))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f));
}
else if (Input.GetMouseButtonDown(2))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f));
}
else if (SvermConfigManagement.RavagerKey.Value.IsDown() && Time.time >= nextTauntAt)
{
nextTauntAt = Time.time + SvermConfig.RavagerTauntCooldownSeconds;
StartCoroutine(TauntRoutine());
}
}
/// <summary>
/// One swing: play the clip, wait for the moment it should land, hit whatever is there,
/// then hold isAttacking until the swing is fully spent. FenrirFormBehavior.ClawRoutine in
/// every particular except the damage itself, which here is the Brute's own real numbers
/// (SvermRavagerAttacks) instead of one tuned float.
/// </summary>
private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, float radius,
float hitDelay, float lockDuration)
{
isAttacking = true;
if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f);
if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger))
{
anim.SetTrigger(profile.Trigger);
}
yield return new WaitForSeconds(hitDelay);
ExecuteDamage(profile, radius);
float remaining = lockDuration - hitDelay;
if (remaining > 0f) yield return new WaitForSeconds(remaining);
isAttacking = false;
}
/// <summary>
/// The taunt, played as a short-cooldown AoE around the player rather than a forward
/// swing - the roar reaches out in every direction, so the sphere is centred on the
/// player instead of offset ahead of them the way AttackRoutine's three do. Deliberately
/// silent: no message, no status effect, nothing in a corner of the screen - just the
/// animation, the sound if one resolves, and the hit.
/// </summary>
private System.Collections.IEnumerator TauntRoutine()
{
isAttacking = true;
SvermRavagerAttacks.Profile profile = SvermRavagerAttacks.Taunt;
if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f);
if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger))
{
anim.SetTrigger(profile.Trigger);
}
PlaySound(SvermConfig.RavagerTauntSoundEffects);
yield return new WaitForSeconds(0.3f);
Player player = Player.m_localPlayer;
if (player != null)
{
ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage);
}
yield return new WaitForSeconds(0.4f);
isAttacking = false;
}
/// <summary>Tries each candidate in order and plays the first that resolves, same as SvermRavagerForm.PlayEffect.</summary>
private static void PlaySound(string[] candidates)
{
Player player = Player.m_localPlayer;
if (player == null) return;
foreach (string name in candidates)
{
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(name);
if (prefab == null) continue;
Object.Instantiate(prefab, player.transform.position, Quaternion.identity);
return;
}
}
/// <summary>
/// FenrirBehaviors.ExecuteClawDamage, unchanged in shape: a sphere swept against the same
/// broad layer mask every melee form in this mod already uses.
/// </summary>
private void ExecuteDamage(SvermRavagerAttacks.Profile profile, float radius)
{
Player player = Player.m_localPlayer;
if (player == null) return;
float reach = SvermConfigManagement.RavagerAttackOffset;
Vector3 attackPoint = player.transform.position + player.transform.forward * reach + Vector3.up;
ApplyDamageInSphere(attackPoint, radius, profile.Damage);
}
/// <summary>
/// The actual sweep, shared by every attack this form has (the three forward swings and
/// the taunt's own AoE) - only the sphere's centre and radius differ between them.
///
/// m_skill is Swords, deliberately NOT Unarmed: Sverm_Damage_Patch rewrites any Unarmed
/// hit from a Sverm into the Chitin Claws' own tier damage, and that patch fires for THIS
/// call too, since it hooks Character.Damage itself rather than caring who dealt the hit.
/// Swords keeps that rewrite from overwriting the Brute's real numbers with the claws'.
/// </summary>
private static void ApplyDamageInSphere(Vector3 center, float radius, HitData.DamageTypes damage)
{
Player player = Player.m_localPlayer;
if (player == null) return;
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece",
"piece_nonsolid", "terrain", "character", "character_net", "character_ghost",
"hitbox", "character_noenv", "vehicle");
Collider[] hits = Physics.OverlapSphere(center, radius, layerMask);
var hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == player.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == player.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target == null) continue;
if (target is Character characterTarget && characterTarget == player) continue;
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null)
{
if (hitObjects.Contains(targetObj)) continue;
hitObjects.Add(targetObj);
}
Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - player.transform.position).normalized;
HitData hitData = new HitData();
hitData.m_damage = damage;
hitData.m_point = targetCenter;
hitData.m_dir = dirToTarget;
hitData.m_pushForce = 40f;
hitData.m_skill = Skills.SkillType.Swords;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 100;
hitData.SetAttacker(player);
target.Damage(hitData);
}
}
}
}