RacesOfValheim/JotunnModStub/Fenrir/FenrirBehaviors.cs
2026-09-24 10:30:39 +02:00

1283 lines
54 KiB
C#

using System.Collections;
using BepInEx;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
using UnityEngine.UI; // Added for UI
namespace RacesOfValheim
{
/// <summary>
/// Howl vocalisation, borrowed from the real creature instead of guessed at. Wolves and their
/// kin do not carry a standalone "sfx_wolf_howl"-style prefab that PlaySFX's
/// PrefabManager.Cache lookup could ever find - dumpdverger's own hierarchy dump for
/// Fenring_Cultist shows no ZSFX anywhere on it.
///
/// BaseAI.m_idleSound was the first guess and was wrong in a quieter way: it is real, but it
/// is the creature's passive ambient noise (DoIdleSound, on a timer while it is doing nothing
/// in particular) - a small grunt, not a howl, and it played back sounding like whatever
/// generic "the form did something" cue the transformation itself already uses. What a
/// creature actually vocalises WHEN IT SPOTS SOMETHING is BaseAI.m_alertedEffects, fired from
/// SetAlerted(true) - reading that off the real "Fenring"/"Fenring_Cultist" prefab and calling
/// Create() plays the same aggressive bark the creature itself makes going on alert.
/// </summary>
internal static class FenrirCreatureSound
{
public static void PlayHowl(string sourcePrefabName, Vector3 position)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefabName);
BaseAI ai = source != null ? source.GetComponent<BaseAI>() : null;
if (ai == null || ai.m_alertedEffects == null)
{
Jotunn.Logger.LogWarning($"[FenrirForm] No BaseAI.m_alertedEffects found on '{sourcePrefabName}'.");
return;
}
ai.m_alertedEffects.Create(position, Quaternion.identity);
}
}
/// <summary>
/// The attack half of somebody else's form: the owner's client publishes each trigger it fires
/// on its own copy of the Animator, RemoteFenrirAnimator replays it on the copy every other
/// client sees. The running count rides along because an unchanged ZDO string would never
/// re-fire a Unity Animator trigger when the same bite lands twice in a row - the same trick as
/// DrakeFormBehavior.AttackTriggerKey and SvermRavagerForm.AttackTriggerKey.
/// </summary>
public static class FenrirAttackSync
{
public const string Key = "RacesOfValheim_FenrirAttack";
private static int seq = 0;
// The cultist's flame is a held bool on the Animator, not a one-shot trigger, so it gets a
// key of its own: a sequence number would say "it started" but never "it stopped".
public const string FireKey = "RacesOfValheim_FenrirFire";
/// <summary>
/// The flame the cultist breathes, parented to the given player so it follows them. One
/// place for it because the owner's own copy and every onlooker's copy have to look alike.
/// </summary>
public static GameObject SpawnFlames(Player player)
{
if (player == null || ZNetScene.instance == null) return null;
// Un effetto che dura nel tempo, trovato dai log!
GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames");
if (fireVfx == null) return null;
GameObject instance = Object.Instantiate(fireVfx, player.transform.position + Vector3.up * 1.5f + player.transform.forward, player.transform.rotation, player.transform);
// Aumentiamo la durata delle particelle del 20%
foreach (ParticleSystem ps in instance.GetComponentsInChildren<ParticleSystem>())
{
var main = ps.main;
main.startLifetimeMultiplier *= 1.2f;
}
return instance;
}
public static void PublishFire(bool on)
{
Player player = Player.m_localPlayer;
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
nview.GetZDO().Set(FireKey, on);
}
/// <summary>
/// Publishes a trigger, and with it the swing's sound: the candidate prefab names in the
/// order the owner's own PlaySFX would try them, or "@Creature" for a howl borrowed from
/// that creature's alert effect. Only the opening cue rides along; the impact sounds are
/// decided by what the swing hits, which an onlooker's client never works out.
/// </summary>
public static void Publish(string trigger, params string[] sfx)
{
Player player = Player.m_localPlayer;
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
seq++;
string payload = trigger + "#" + seq;
if (sfx != null && sfx.Length > 0) payload += "#" + string.Join("|", sfx);
nview.GetZDO().Set(Key, payload);
}
}
/// <summary>
/// The animation half of somebody else's form.
///
/// The four behaviours below drive their model's Animator from the player's own, and every
/// one of them runs on the transformed player's client only: FenrirRace.ExecuteTransformation
/// is what adds them, and they read Player.m_localPlayer throughout. RacesVisualController
/// spawns the same model on every other client from the ZDO, and used to spawn nothing else -
/// no parameter was ever written to that copy's Animator, so it sat in its controller's
/// default state and slid across the terrain. The wolf's owner saw a wolf running; everyone
/// else saw a statue on rails.
///
/// This is the piece that was missing, and it is the arrangement Skadi already uses for its
/// remote dragons (RemoteSkadiAnimator). The parameters come from the remote player's own
/// Visual Animator, which ZSyncAnimation keeps fed over the network for every character a
/// client can see - hiding the body hides renderers, not the animation - so the form walks,
/// runs, jumps and creeps exactly when the real player does.
///
/// Kept next to the four local behaviours on purpose: this mirrors the movement half of their
/// Update, and the two have to be changed together.
///
/// Attacks are triggers fired from input on the owner's client; FenrirAttackSync publishes
/// each one on the ZDO and this component replays it below.
/// </summary>
public class RemoteFenrirAnimator : MonoBehaviour
{
private Player player;
private Animator playerAnim;
private Animator formAnim;
private ZNetView nview;
private string lastAttack;
private GameObject flames;
// The flames hang off the player, not this model, so they outlive it unless taken down.
private void OnDestroy()
{
if (flames != null) Destroy(flames);
}
private void Update()
{
// Resolved here rather than in Start: the model is instantiated under a player who may
// still be assembling their own rig on the frame it arrives.
if (player == null) player = GetComponentInParent<Player>();
if (player == null) return;
if (formAnim == null) formAnim = GetComponent<Animator>() ?? GetComponentInChildren<Animator>();
if (playerAnim == null)
{
Transform visual = player.transform.Find("Visual");
if (visual != null) playerAnim = visual.GetComponent<Animator>();
}
if (formAnim == null || playerAnim == null) return;
ReplayAttack();
ReplayFire();
bool grounded = playerAnim.GetBool("onGround");
// All four borrowed creatures answer to these, and they are still written through
// try/catch the way the local behaviours do it: a controller missing one of them would
// otherwise throw once per frame, for every onlooker.
try { formAnim.SetBool("onGround", grounded); } catch {}
try { formAnim.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {}
// The same three cases the local behaviours use, so both views of the same wolf agree:
// airborne and crouching each read as standing still. Player.IsCrouching answers off
// the animator's current state, which is replicated, so it is true here too.
bool still = !grounded || player.IsCrouching();
try { formAnim.SetFloat("forward_speed", still ? 0f : playerAnim.GetFloat("forward_speed")); } catch {}
try { formAnim.SetFloat("sideway_speed", still ? 0f : playerAnim.GetFloat("sideway_speed")); } catch {}
}
// Written every frame while the flag is set, and only when the controller has the bool: a
// wolf or a Ulv has no "attack_fire", and the ZDO key is only ever true for the cultist.
private void ReplayFire()
{
if (nview == null || !nview.IsValid()) return;
bool fire = nview.GetZDO().GetBool(FenrirAttackSync.FireKey, false);
// The breath itself: up while the flag is, gone when it drops. Only the cultist ever
// sets the flag, so no other form can grow flames here.
if (fire && flames == null)
{
flames = FenrirAttackSync.SpawnFlames(player);
// The roar that opens the breath, once per start, the same cue the owner hears.
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>("sfx_cultist_attack_fire_start");
if (sfx != null) Instantiate(sfx, player.transform.position, Quaternion.identity);
}
else if (!fire && flames != null) { Destroy(flames); flames = null; }
foreach (AnimatorControllerParameter p in formAnim.parameters)
{
if (p.type == AnimatorControllerParameterType.Bool && p.name == "attack_fire")
{
formAnim.SetBool("attack_fire", fire);
break;
}
}
}
private void PlayAttackSound(string[] names)
{
foreach (string name in names)
{
if (name.StartsWith("@"))
{
FenrirCreatureSound.PlayHowl(name.Substring(1), player.transform.position);
return;
}
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
Instantiate(sfx, player.transform.position, Quaternion.identity);
return;
}
}
}
private void ReplayAttack()
{
if (nview == null) nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
string current = nview.GetZDO().GetString(FenrirAttackSync.Key, "");
// First look at the ZDO only records what is already there, so a trigger left over from
// an earlier form does not replay the instant this model is built.
if (lastAttack == null) { lastAttack = current; return; }
if (string.IsNullOrEmpty(current) || current == lastAttack) return;
lastAttack = current;
string[] parts = current.Split('#');
string trigger = parts[0];
if (parts.Length > 2) PlayAttackSound(parts[2].Split('|'));
// Only the triggers this particular borrowed controller actually has: the four forms
// share none of the attack names but the taunt.
foreach (AnimatorControllerParameter p in formAnim.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger && p.name == trigger)
{
formAnim.SetTrigger(trigger);
break;
}
}
}
}
public class FenrirFormBehavior : MonoBehaviour
{
private Animator playerAnim;
private Animator fenrirAnim;
private bool isAttacking = false;
void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
fenrirAnim = GetComponent<Animator>();
if (fenrirAnim == null) fenrirAnim = GetComponentInChildren<Animator>();
}
void Update()
{
if (playerAnim == null || fenrirAnim == null) return;
// Se stiamo attaccando, l'Update smette di inviare costantemente
// "onGround", inWater, forward_speed ecc. alle variabili di base?
// Meglio continuare a sincronizzare i movimenti base.
if (!isAttacking)
{
bool isGrounded = playerAnim.GetBool("onGround");
fenrirAnim.SetBool("onGround", isGrounded);
fenrirAnim.SetBool("inWater", playerAnim.GetBool("inWater"));
if (!isGrounded)
{
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
}
else
{
if (Player.m_localPlayer.IsCrouching())
{
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
}
else
{
fenrirAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed"));
fenrirAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed"));
}
}
if (isGrounded && RaceInput.Allowed)
{
if (FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{
StartCoroutine(HowlRoutine());
}
else if (RaceInput.AttackDown(1)) // Tasto destro (Heavy Claw)
{
StartCoroutine(ClawRoutine("attack_claw1", FenrirConfig.FenringHeavyClawDamage.Value, 1.2f, 0.5f));
}
else if (RaceInput.AttackDown(0)) // Tasto sinistro
{
StartCoroutine(ClawRoutine("attack_claw0", FenrirConfig.FenringLightClawDamage.Value, 1.0f, 0.4f));
}
else if (RaceInput.AttackDown(2)) // Tasto centrale
{
StartCoroutine(JumpAttackRoutine());
}
}
}
}
private void PlaySFX(params string[] prefabNames)
{
foreach (string name in prefabNames)
{
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity);
return;
}
}
Jotunn.Logger.LogWarning($"[FenrirForm] Nessun suono trovato tra: {string.Join(", ", prefabNames)}");
}
private IEnumerator HowlRoutine()
{
isAttacking = true;
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
fenrirAnim.SetTrigger("attack_taunt");
FenrirAttackSync.Publish("attack_taunt", "@Fenring");
FenrirCreatureSound.PlayHowl("Fenring", Player.m_localPlayer.transform.position);
yield return new WaitForSeconds(2.0f);
isAttacking = false;
}
private IEnumerator ClawRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{
isAttacking = true;
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
fenrirAnim.SetTrigger(triggerName);
FenrirAttackSync.Publish(triggerName, "sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack");
PlaySFX("sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack");
yield return new WaitForSeconds(dmgDelay);
if (ZNetScene.instance != null)
{
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_fenring_attack");
if (attackSfx != null)
{
Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity);
}
}
ExecuteClawDamage(baseDamage);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
fenrirAnim.ResetTrigger(triggerName);
isAttacking = false;
}
private IEnumerator JumpAttackRoutine()
{
isAttacking = true;
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
fenrirAnim.SetTrigger("attack_jump");
FenrirAttackSync.Publish("attack_jump");
// Aspettiamo che l'animazione si carichi (0.75s)
yield return new WaitForSeconds(0.75f);
if (ZNetScene.instance != null)
{
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_fenring_attack");
if (attackSfx != null)
{
Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity);
}
}
// Invece di una singola spinta di velocità (che viene subito annullata da Valheim),
// muoviamo esplicitamente il personaggio fotogramma per fotogramma per 0.2 secondi
float dashDuration = 0.2f;
float elapsedDash = 0f;
while (elapsedDash < dashDuration)
{
if (Player.m_localPlayer != null)
{
Rigidbody rb = Player.m_localPlayer.GetComponent<Rigidbody>();
if (rb != null)
{
Vector3 dashVelocity = Player.m_localPlayer.transform.forward * FenrirConfig.FenringJumpDashSpeed.Value;
// Spinta verso l'alto solo nella prima metà dello scatto
if (elapsedDash < dashDuration / 2f)
{
dashVelocity += Vector3.up * FenrirConfig.FenringJumpDashUpwardSpeed.Value;
}
rb.MovePosition(rb.position + dashVelocity * Time.fixedDeltaTime);
}
}
elapsedDash += Time.fixedDeltaTime;
yield return new WaitForFixedUpdate();
}
// Infliggiamo il danno al termine dello scatto
ExecuteClawDamage(FenrirConfig.FenringJumpAttackDamage.Value);
// Tempo per riprendersi dall'atterraggio prima di potersi muovere di nuovo
yield return new WaitForSeconds(0.55f);
fenrirAnim.ResetTrigger("attack_jump");
isAttacking = false;
}
private void ExecuteClawDamage(float baseDamage)
{
if (Player.m_localPlayer == null) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
float attackRadius = FenrirConfig.FenringAttackRadius.Value;
float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
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(attackPoint, attackRadius, layerMask);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) 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 - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle < 70f)
{
Vector3 eyePos = playerPos + Vector3.up * 1.5f;
if (!Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece")))
{
HitData hitData = new HitData();
hitData.m_damage.m_slash = totalDamage;
hitData.m_pushForce = FenrirConfig.FenringPushForce.Value;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer);
target.Damage(hitData);
}
}
}
}
}
}
// --- CLASSE CUSTOM PER L'ATTACCO "FIRE" DEL CULTIST ---
public class CultistFormBehavior : MonoBehaviour
{
private Animator playerAnim;
private Animator cultistAnim;
private bool isAttacking = false;
private bool isShootingFire = false;
private float fireTimer = 0f;
void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
cultistAnim = GetComponent<Animator>();
if (cultistAnim == null) cultistAnim = GetComponentInChildren<Animator>();
}
void Update()
{
if (playerAnim == null || cultistAnim == null) return;
if (!isAttacking)
{
bool isGrounded = playerAnim.GetBool("onGround");
cultistAnim.SetBool("onGround", isGrounded);
cultistAnim.SetBool("inWater", playerAnim.GetBool("inWater"));
if (!isGrounded)
{
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
}
else
{
// Se tiene premuto Ctrl (Crouch), rallenta o ferma il movimento per preparare l'attacco
if (Player.m_localPlayer.IsCrouching())
{
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
}
else
{
cultistAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed"));
cultistAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed"));
}
}
if (isGrounded)
{
// Gated per-read rather than around the block, so opening a GUI mid-stream
// still falls through to StopFire() instead of leaving the flames running.
bool canAct = RaceInput.Allowed;
// Fire attack on Right Click
if (canAct && RaceInput.AttackHeld(1))
{
if (Player.m_localPlayer.GetEitr() > 0)
{
if (!isShootingFire)
{
StartFire();
}
else
{
UpdateFire();
}
}
else if (isShootingFire)
{
StopFire();
}
}
else if (isShootingFire)
{
StopFire();
}
if (canAct && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{
StartCoroutine(HowlRoutine());
}
// Attacks on Left Click
if (canAct && RaceInput.AttackDown(0) && !isShootingFire)
{
StartCoroutine(ClawRoutine()); // Single claw
}
// Double claw on Middle Click
else if (canAct && RaceInput.AttackDown(2) && !isShootingFire)
{
StartCoroutine(DoubleClawRoutine());
}
}
else if (isShootingFire)
{
StopFire();
}
}
}
private void PlaySFX(params string[] prefabNames)
{
foreach (string name in prefabNames)
{
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity);
return;
}
}
Jotunn.Logger.LogWarning($"[CultistForm] Nessun suono trovato tra: {string.Join(", ", prefabNames)}");
}
private IEnumerator HowlRoutine()
{
isAttacking = true;
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
// Cultist ha una vera e propria animazione di "taunt"
cultistAnim.SetTrigger("attack_taunt");
FenrirAttackSync.Publish("attack_taunt", "@Fenring_Cultist");
FenrirCreatureSound.PlayHowl("Fenring_Cultist", Player.m_localPlayer.transform.position);
// Durata approssimativa dell'animazione di taunt
yield return new WaitForSeconds(2.0f);
isAttacking = false;
}
private GameObject fireEffectInstance;
private void StartFire()
{
if (Player.m_localPlayer == null || isShootingFire) return;
isShootingFire = true;
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
cultistAnim.SetBool("attack_fire", true);
FenrirAttackSync.PublishFire(true);
PlaySFX("sfx_cultist_attack_fire_start");
cultistAnim.SetTrigger("attack_flames");
FenrirAttackSync.Publish("attack_flames");
if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer);
}
private void UpdateFire()
{
Player.m_localPlayer.UseEitr(FenrirConfig.CultistFireEitrDrainPerSecond.Value * Time.deltaTime);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
fireTimer += Time.deltaTime;
if (fireTimer >= 0.2f) // Damage tick every 0.2s
{
fireTimer = 0f;
ExecuteFireDamage();
}
}
// Leaving the form mid-flame must not leave the flag up for onlookers.
private void OnDestroy()
{
if (isShootingFire) FenrirAttackSync.PublishFire(false);
}
private void StopFire()
{
isShootingFire = false;
cultistAnim.ResetTrigger("attack_flames");
FenrirAttackSync.PublishFire(false);
if (fireEffectInstance != null)
{
Destroy(fireEffectInstance);
fireEffectInstance = null;
}
}
private void ExecuteFireDamage()
{
if (Player.m_localPlayer == null) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 2.5f + Vector3.up * 1f;
float attackRadius = FenrirConfig.CultistFireAttackRadius.Value;
float magicSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.ElementalMagic);
float baseFireDamage = FenrirConfig.CultistFireDamagePerTick.Value;
float totalDamage = baseFireDamage + (magicSkillLevel * FenrirConfig.CultistFireMagicSkillScaling.Value);
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(attackPoint, attackRadius, layerMask);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) 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 - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle < 45f)
{
HitData hitData = new HitData();
hitData.m_damage.m_fire = totalDamage;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.ElementalMagic;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.SetAttacker(Player.m_localPlayer);
target.Damage(hitData);
if (ZNetScene.instance != null)
{
GameObject hitFx = ZNetScene.instance.GetPrefab("vfx_FireballHit");
if (hitFx != null) Instantiate(hitFx, targetCenter, Quaternion.identity);
}
}
}
}
}
private IEnumerator ClawRoutine()
{
isAttacking = true;
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
// Per il Cultista usiamo esplicitamente il trigger dell'artigliata
cultistAnim.SetTrigger("attack_claw");
FenrirAttackSync.Publish("attack_claw", "sfx_cultist_attack", "sfx_fenring_attack", "sfx_wolf_attack");
yield return new WaitForSeconds(0.4f);
PlaySFX("sfx_cultist_attack", "sfx_fenring_attack", "sfx_wolf_attack");
ExecuteClawDamage(FenrirConfig.CultistClawDamage.Value);
float remainingTimeToIdle = 0.5f - 0.4f;
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
cultistAnim.ResetTrigger("attack_claw");
isAttacking = false;
}
private IEnumerator DoubleClawRoutine()
{
isAttacking = true;
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
cultistAnim.SetTrigger("attack_claw_double");
FenrirAttackSync.Publish("attack_claw_double", "sfx_cultist_attack_double", "sfx_cultist_attack", "sfx_fenring_attack");
// L'animazione double claw è più lunga, facciamo il danno un po' dopo
yield return new WaitForSeconds(0.6f);
PlaySFX("sfx_cultist_attack_double", "sfx_cultist_attack", "sfx_fenring_attack");
ExecuteClawDamage(FenrirConfig.CultistDoubleClawDamage.Value);
// Attendiamo che l'animazione finisca (locking del giocatore)
// L'animazione doppia del cultista dura circa 1.5 - 2 secondi
yield return new WaitForSeconds(1.2f);
cultistAnim.ResetTrigger("attack_claw_double");
isAttacking = false;
}
private void ExecuteClawDamage(float baseDamage)
{
if (Player.m_localPlayer == null) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
float attackRadius = FenrirConfig.CultistAttackRadius.Value;
float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
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(attackPoint, attackRadius, layerMask);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) 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 - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle < 70f)
{
Vector3 eyePos = playerPos + Vector3.up * 1.5f;
if (!Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece")))
{
HitData hitData = new HitData();
hitData.m_damage.m_slash = totalDamage;
hitData.m_pushForce = FenrirConfig.CultistPushForce.Value;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer);
target.Damage(hitData);
}
}
}
}
}
}
public class WolfFormBehavior : MonoBehaviour
{
private Animator playerAnim;
private Animator wolfAnim;
private bool isAttacking = false;
void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
wolfAnim = GetComponent<Animator>();
if (wolfAnim == null) wolfAnim = GetComponentInChildren<Animator>();
}
void Update()
{
if (playerAnim == null || wolfAnim == null) return;
if (!isAttacking)
{
bool isGrounded = playerAnim.GetBool("onGround");
try { wolfAnim.SetBool("onGround", isGrounded); } catch {}
try { wolfAnim.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {}
if (!isGrounded)
{
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
}
else
{
if (Player.m_localPlayer.IsCrouching())
{
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
}
else
{
try { wolfAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed")); } catch {}
try { wolfAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")); } catch {}
}
}
if (isGrounded && RaceInput.Allowed)
{
if (RaceInput.AttackDown(0)) // Left Click
{
StartCoroutine(WolfAttackRoutine("attack1", FenrirConfig.WolfAttack1Damage.Value, 0.6f, 0.2f));
}
else if (RaceInput.AttackDown(1)) // Right Click
{
StartCoroutine(WolfAttackRoutine("attack2", FenrirConfig.WolfAttack2Damage.Value, 0.8f, 0.3f));
}
else if (RaceInput.AttackDown(2)) // Middle Click
{
StartCoroutine(WolfAttackRoutine("attack3", FenrirConfig.WolfAttack3Damage.Value, 1.0f, 0.4f));
}
}
}
}
private void PlaySFX(params string[] prefabNames)
{
foreach (string name in prefabNames)
{
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity);
return;
}
}
}
private IEnumerator WolfAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{
isAttacking = true;
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
wolfAnim.SetTrigger(triggerName);
FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack");
yield return new WaitForSeconds(dmgDelay);
if (ZNetScene.instance != null)
{
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack");
if (attackSfx != null)
{
Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity);
}
}
ExecuteBiteDamage(baseDamage);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
wolfAnim.ResetTrigger(triggerName);
isAttacking = false;
}
private void ExecuteBiteDamage(float baseDamage)
{
if (Player.m_localPlayer == null) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
// Il lupo è basso, abbassiamo l'altezza dell'attacco
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f;
float attackRadius = FenrirConfig.WolfAttackRadius.Value;
float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
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(attackPoint, attackRadius, layerMask);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) 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 - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle < 70f)
{
Vector3 eyePos = playerPos + Vector3.up * 1.0f;
if (!Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece")))
{
HitData hitData = new HitData();
hitData.m_damage.m_slash = totalDamage;
hitData.m_pushForce = FenrirConfig.WolfPushForce.Value;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer);
target.Damage(hitData);
}
}
}
}
}
}
// --- CLASSE CUSTOM PER L'ULV ---
public class UlvFormBehavior : MonoBehaviour
{
private Animator playerAnim;
private Animator ulvAnim;
private bool isAttacking = false;
void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
ulvAnim = GetComponent<Animator>();
if (ulvAnim == null) ulvAnim = GetComponentInChildren<Animator>();
}
void Update()
{
if (Player.m_localPlayer == null || playerAnim == null || ulvAnim == null) return;
if (!isAttacking)
{
bool isGrounded = playerAnim.GetBool("onGround");
try { ulvAnim.SetBool("onGround", isGrounded); } catch {}
try { ulvAnim.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {}
if (!isGrounded)
{
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
}
else
{
if (Player.m_localPlayer.IsCrouching())
{
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
}
else
{
try { ulvAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed")); } catch {}
try { ulvAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")); } catch {}
}
}
if (isGrounded && RaceInput.Allowed)
{
if (RaceInput.AttackDown(0)) // Left Click
{
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvBiteDamage.Value, 0.6f, 0.2f));
}
else if (RaceInput.AttackDown(1)) // Right Click
{
// Right click uses bite but as a heavier attack since slash is moved to jump
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvHeavyBiteDamage.Value, 0.8f, 0.3f));
}
else if (RaceInput.AttackDown(2)) // Middle Click
{
StartCoroutine(UlvJumpAttackRoutine());
}
}
}
}
private void PlaySFX(params string[] prefabNames)
{
foreach (string name in prefabNames)
{
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity);
return;
}
}
}
private IEnumerator UlvAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{
isAttacking = true;
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
try { ulvAnim.SetTrigger(triggerName); } catch {}
FenrirAttackSync.Publish(triggerName, "sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack");
// Scegli il suono appropriato per l'attacco
if (triggerName == "attack_bite")
{
PlaySFX("sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack");
}
else
{
PlaySFX("sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack");
}
yield return new WaitForSeconds(dmgDelay);
if (ZNetScene.instance != null)
{
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit");
if (attackSfx != null)
{
Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity);
}
}
ExecuteBiteDamage(baseDamage);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
try { ulvAnim.ResetTrigger(triggerName); } catch {}
isAttacking = false;
}
private void ExecuteBiteDamage(float baseDamage)
{
if (Player.m_localPlayer == null) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f;
float attackRadius = FenrirConfig.UlvAttackRadius.Value;
float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
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(attackPoint, attackRadius, layerMask);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) 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 - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle < 70f)
{
Vector3 eyePos = playerPos + Vector3.up * 1.0f;
if (!Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece")))
{
HitData hitData = new HitData();
hitData.m_damage.m_slash = totalDamage;
hitData.m_pushForce = FenrirConfig.UlvPushForce.Value;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer);
target.Damage(hitData);
}
}
}
}
}
private IEnumerator UlvJumpAttackRoutine()
{
isAttacking = true;
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
try { ulvAnim.SetTrigger("attack_slash"); } catch {}
FenrirAttackSync.Publish("attack_slash", "sfx_ulv_attack", "sfx_wolf_attack");
PlaySFX("sfx_ulv_attack", "sfx_wolf_attack");
yield return new WaitForSeconds(0.3f); // Wait 0.3s before leaping
// Leap forward (+50% range)
float leapDuration = 0.25f;
float leapSpeed = FenrirConfig.UlvLeapSpeed.Value;
float elapsed = 0f;
while (elapsed < leapDuration)
{
if (Player.m_localPlayer != null)
{
Vector3 moveDir = Player.m_localPlayer.transform.forward;
Player.m_localPlayer.transform.position += moveDir * leapSpeed * Time.deltaTime;
}
elapsed += Time.deltaTime;
yield return null;
}
if (ZNetScene.instance != null)
{
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit");
if (attackSfx != null)
{
Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity);
}
}
ExecuteBiteDamage(FenrirConfig.UlvJumpAttackDamage.Value);
yield return new WaitForSeconds(0.4f);
try { ulvAnim.ResetTrigger("attack_slash"); } catch {}
isAttacking = false;
}
}
}