feat(aswid): bat flies on the Skadi's directed flight

The bat flew on vanilla's debug-fly flag: 50 m/s, free, blind to carry
weight, and invisible to monsters until six patches lied about the flag.
It now flies on m_flying with the drake's controls, moved out of
SkadiPatches into a shared DirectedFlight core that both forms feed
their own numbers into. Powered flight and the sprint cost stamina; out
of stamina the bat glides. Encumbered flight costs 15% more, or is
blocked with 'While Encumbered'. Optional duration and cooldown, off by
default. The aggro/damage patches, the debug-fly speed patch and their
three settings are removed; the drake's behaviour is unchanged.
This commit is contained in:
kanym 2026-10-26 14:26:42 +01:00
commit 77cdc67e97
19 changed files with 534 additions and 516 deletions

View file

@ -1,182 +0,0 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Why nothing in Valheim ever attacked the bat, and the smallest honest fix for it.
///
/// The bat flies on Player.m_debugFly - the developer no-clip flag - because that is the only
/// flight vanilla actually has, and it is what BatFormBehavior sets and WarVultureMount reuses.
/// What nobody noticed is that vanilla reads that same flag as "this player is not really
/// here". Six places, all read out of assembly_valheim with Cecil rather than guessed:
///
/// BaseAI.CanHearTarget - first line: the target is a Player in debug fly -> return false.
/// BaseAI.CanSeeTarget - the same first line, the same false.
/// BaseAI.FindEnemy - its HuntPlayer fallback throws the player away for the same reason.
/// MonsterAI.UpdateSleep - a sleeping monster refuses to wake for one, twice over.
/// Character.ApplyDamage - first line: IsDebugFlying -> return, the hit does nothing.
/// Character.RPC_Damage - the same.
///
/// So the bat was never merely ignored: it was invulnerable as well, and both facts came out of
/// the one flag. There was nothing wrong with the Aswid's own code, which is why nothing in it
/// looked wrong.
///
/// The fix keeps the flag - it IS the flight - and lies about it in exactly the places that
/// decide aggro and damage, and nowhere else:
///
/// Player.InDebugFlyMode() is forced false for a bat unconditionally. That is safe, and it is
/// the reason this file is short: a scan of the whole assembly says that method has
/// exactly three callers, and all three are the sensing paths listed above. No part of
/// flight, camera, stamina or motion goes through it.
/// Player.IsDebugFlying() is NOT forced false, because Character.UpdateMotion reads it and
/// that read is what holds the bat in the air. It is only forced false while the call
/// stack is inside one of the three vanilla methods that must not honour it, which is
/// what the depth counter below is for.
///
/// Both halves sit behind their own config toggle, so a bat can be made visible-but-immortal,
/// or put back the way it was, without touching code.
/// </summary>
public static class AswidBatForm
{
/// <summary>
/// The ZDO flag AswidRace writes when the form goes up. Replicated, so it answers for
/// remote players too - which matters here, because the machine asking "is this player a
/// bat" is whichever one owns the monster, not the bat's own.
/// </summary>
public const string BatZdoKey = "Aswid_IsBatForm";
private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
// How deep we currently are inside vanilla calls that must not see the debug-fly flag. A
// counter and not a bool: ApplyDamage runs inside RPC_Damage, so the frames nest.
private static int unmaskDepth;
public static bool Unmasked => unmaskDepth > 0;
public static void PushUnmask() { unmaskDepth++; }
public static void PopUnmask() { if (unmaskDepth > 0) unmaskDepth--; }
/// <summary>
/// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true
/// on every client, and the status effect covers the local player during the frames of the
/// transform where the ZDO write has not landed yet.
/// </summary>
public static bool IsBat(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
return player == Player.m_localPlayer &&
player.GetSEMan() != null &&
player.GetSEMan().HaveStatusEffect(BatFormHash);
}
}
/// <summary>
/// The whole of the aggro fix. See AswidBatForm for why patching this one method flat is safe,
/// and why patching IsDebugFlying flat would drop the bat out of the sky instead.
/// </summary>
[HarmonyPatch(typeof(Player), "InDebugFlyMode")]
public static class Aswid_BatIsVisibleToAI_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result) return;
if (AswidConfig.BatFormAggro != null && !AswidConfig.BatFormAggro.Value) return;
if (AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// The scoped half. Only ever fires inside the three vanilla methods that push the counter, and
/// only for a player who is a bat - so the flag still reads true everywhere flight, motion, the
/// camera and Player.UpdateStats look at it.
/// </summary>
[HarmonyPatch(typeof(Player), "IsDebugFlying")]
public static class Aswid_BatIsDebugFlying_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result || !AswidBatForm.Unmasked) return;
if (AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// A hit landing on a bat. Finalizer rather than Postfix throughout this file: the counter has
/// to come back down even when the patched method throws, and a Postfix does not run then. A
/// void Finalizer leaves the original exception alone, so nothing is swallowed either.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_BatTakesDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = (AswidConfig.BatFormVulnerable == null || AswidConfig.BatFormVulnerable.Value)
&& __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>The networked half of the same thing: a hit sent by another machine.</summary>
[HarmonyPatch(typeof(Character), "RPC_Damage")]
public static class Aswid_BatTakesRemoteDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = (AswidConfig.BatFormVulnerable == null || AswidConfig.BatFormVulnerable.Value)
&& __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>
/// Sleepers. Unlike the two above this cannot pre-check who the player is - UpdateSleep picks
/// the closest one itself, and that may be a remote bat - so the counter goes up for the whole
/// call and the per-player test happens in the IsDebugFlying postfix, where it costs nothing:
/// that postfix only runs at all for a character who is already flying.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateSleep")]
public static class Aswid_BatWakesSleepers_Patch
{
public static void Prefix(ref bool __state)
{
__state = AswidConfig.BatFormAggro == null || AswidConfig.BatFormAggro.Value;
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>
/// Dying as a bat only became possible with the patches above, and the revert path could not
/// handle it: AswidRace.Update() returns early on IsDead(), so the coroutine that takes the
/// form down never starts. The debug-fly flag would stay on and the ZDO would stay true, which
/// is a respawned player floating over the ground with a bat drawn on them.
/// </summary>
[HarmonyPatch(typeof(Player), "OnDeath")]
public static class Aswid_BatDiesAsBat_Patch
{
public static void Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (AswidRace.Instance == null) return;
AswidRace.Instance.HardResetBatForm();
}
}
}

View file

@ -1,57 +0,0 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// How fast the bat flies, as a factor on vanilla's own debug-fly speed.
///
/// The form flies on Player.m_debugFly (see AswidBatForm for why), so its speed is whatever
/// Character.UpdateDebugFly decides. Read out of assembly_valheim rather than assumed, that
/// method ends with:
///
/// m_currentVel = Vector3.Lerp(m_currentVel, b, 0.5f);
/// m_body.linearVelocity = m_currentVel;
///
/// where b is m_moveDir times m_debugFlySpeed - a public STATIC INT, 20 by default, times 2.5
/// while the run key is held.
///
/// Two ways to make that faster were rejected before this one:
///
/// Retuning m_debugFlySpeed around the call. It is shared by every character in the game and
/// it is an int, so a 1.35x multiplier would land on 27 and a 1.37x on the same 27 - the
/// slider would move in 5% steps and would be writing a global while it did it.
///
/// Scaling m_currentVel itself, which is what WarVultureMount does for the bird. That field
/// is the input to the NEXT frame's lerp, so scaling it feeds back: with a factor s the
/// velocity settles at 0.5s/(1-0.5s) times vanilla, not s times it, and at s >= 2 it does
/// not settle at all.
///
/// So only the rigidbody is scaled, and m_currentVel is left exactly as vanilla wrote it. The
/// lerp keeps smoothing the same trajectory it always did - the ramp up, the ease off, the
/// standstill at zero input - and the bat simply covers it faster. Linear in the slider, with
/// nothing to accumulate.
/// </summary>
[HarmonyPatch(typeof(Character), "UpdateDebugFly")]
public static class Aswid_BatFlightSpeed_Patch
{
public static void Postfix(Character __instance, Vector3 ___m_currentVel, Rigidbody ___m_body)
{
// Bound from RacesOfValheim.Awake(), before harmony.PatchAll() - the null check is for
// the config that failed to bind at all, not for a race between the two.
if (AswidConfig.BatFormFlightSpeed == null) return;
float multiplier = AswidConfig.BatFormFlightSpeed.Value;
if (Mathf.Approximately(multiplier, 1f)) return;
// Local player only. Every other machine's bat moves on its replicated position, and
// scaling velocity here would fight that sync rather than help it.
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
if (___m_body == null) return;
if (!AswidBatForm.IsBat(player)) return;
___m_body.linearVelocity = ___m_currentVel * multiplier;
}
}
}

View file

@ -0,0 +1,59 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Whether a player is a bat, on any client.
///
/// This file used to be AswidBatAggro: while the bat flew on vanilla's debug-fly flag, vanilla
/// read that flag as "this player is not really here" - no monster could see, hear or wake for
/// it, and every hit on it was dropped - and six patches here lied about the flag in exactly
/// those places. The bat now flies on m_flying (DirectedFlight.cs), which vanilla's AI and
/// damage never look at, so monsters notice and hurt it with no help, and the lie went.
/// </summary>
public static class AswidBatForm
{
/// <summary>
/// The ZDO flag AswidRace writes when the form goes up. Replicated, so it answers for
/// remote players too.
/// </summary>
public const string BatZdoKey = "Aswid_IsBatForm";
private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
/// <summary>
/// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true
/// on every client, and the status effect covers the local player during the frames of the
/// transform where the ZDO write has not landed yet.
/// </summary>
public static bool IsBat(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
return player == Player.m_localPlayer &&
player.GetSEMan() != null &&
player.GetSEMan().HaveStatusEffect(BatFormHash);
}
}
/// <summary>
/// The revert path cannot handle a bat that dies: AswidRace.Update() returns early on IsDead(),
/// so the coroutine that takes the form down never starts. The flight flag would stay on and
/// the ZDO would stay true, which is a respawned player floating over the ground with a bat
/// drawn on them.
/// </summary>
[HarmonyPatch(typeof(Player), "OnDeath")]
public static class Aswid_BatDiesAsBat_Patch
{
public static void Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (AswidRace.Instance == null) return;
AswidRace.Instance.HardResetBatForm();
}
}
}

View file

@ -42,12 +42,26 @@ namespace RacesOfValheim
public static ConfigEntry<float> StaminaCostMultiplier;
// ─── Bat Form ────────────────────────────────────────────────────────────
// Both of these undo something vanilla does to any player on the debug-fly flag, which is
// what the bat flies on. See AswidBatAggro for the six vanilla methods involved.
public static ConfigEntry<bool> BatFormAggro;
public static ConfigEntry<bool> BatFormVulnerable;
// A factor on vanilla's debug-fly speed, not a speed in metres - see AswidBatFlight.
public static ConfigEntry<float> BatFormFlightSpeed;
// The bat flies on the same directed flight as the Skadi's drakes (DirectedFlight.cs),
// with its own numbers. It used to fly on vanilla's debug-fly flag: 50 m/s, free, blind
// to carry weight, and ignored by every monster until AswidBatAggro lied to six vanilla
// methods about it. None of that is left.
public enum EncumberedMode { Allowed, Blocked }
public static ConfigEntry<float> BatTurnSpeed;
public static ConfigEntry<float> BatGlideSpeed;
public static ConfigEntry<float> BatBoostSpeed;
public static ConfigEntry<float> BatSprintSpeed;
public static ConfigEntry<float> BatReverseSpeed;
public static ConfigEntry<float> BatLiftoffSpeed;
public static ConfigEntry<float> BatHoverSeconds;
public static ConfigEntry<float> BatPoweredStaminaPerSecond;
public static ConfigEntry<float> BatSprintStaminaPerSecond;
public static ConfigEntry<EncumberedMode> BatEncumbered;
public static ConfigEntry<float> BatEncumberedExtraCost;
public static ConfigEntry<float> BatMaxDuration;
public static ConfigEntry<float> BatDurationPerState;
public static ConfigEntry<float> BatCooldown;
// ─── Vampiric Aura (passive, always active) ──────────────────────────────
public static ConfigEntry<float> AuraTickInterval;
@ -155,12 +169,38 @@ namespace RacesOfValheim
new ConfigDescription("Multiplies every stamina cost: sprinting, swimming, attacks, blocking. 1 is the normal cost, 0.5 half. There is no infinite setting on purpose; set the bonuses above high instead.", new AcceptableValueRange<float>(0.1f, 2f)));
const string batform = "Aswid - Bat Form";
BatFormAggro = config.Bind(batform, "Monsters Notice The Bat", true,
new ConfigDescription("Lets monsters see, hear and wake up for a player in Bat Form. Vanilla refuses to notice anyone flying on the debug-fly flag, which is the flag the form uses - turn this off to go back to a bat nothing ever looks at."));
BatFormVulnerable = config.Bind(batform, "The Bat Can Be Hurt", true,
new ConfigDescription("Lets damage land on a player in Bat Form. Same cause as the setting above: vanilla drops every hit on a debug-flying character. Turn this off for a bat that is noticed and chased but cannot be killed."));
BatFormFlightSpeed = config.Bind(batform, "Flight Speed", 1f,
new ConfigDescription("How fast the bat flies, as a multiplier on the game's own flight speed (20 m/s, and 2.5x that while the run key is held). 1 is untouched, 2 is twice as fast, 0.5 is half. Local only - it changes how your own bat moves, not anyone else's.", new AcceptableValueRange<float>(0.25f, 3f)));
// Same controls as the Skadi's drake: aim with the camera, W beats forward, Shift
// sprints, S beats backwards, and letting go hovers briefly before gliding down.
BatTurnSpeed = config.Bind(batform, "Turn Speed", 180f,
new ConfigDescription("Degrees per second the bat turns towards where you aim.", new AcceptableValueRange<float>(30f, 720f)));
BatGlideSpeed = config.Bind(batform, "Glide Speed", 6f,
new ConfigDescription("Speed while gliding down with no key held, in m/s.", new AcceptableValueRange<float>(0f, 30f)));
// Not "Flight Speed": that key held the old debug-fly multiplier, and an existing .cfg
// would load its 1 here as one metre per second.
BatBoostSpeed = config.Bind(batform, "Boost Speed", 13f,
new ConfigDescription("Speed while holding W, in m/s. Costs the powered stamina below.", new AcceptableValueRange<float>(0f, 60f)));
BatSprintSpeed = config.Bind(batform, "Sprint Speed", 24f,
new ConfigDescription("Speed while holding W and Shift, in m/s. Costs the sprint stamina on top. The old bat flew at 50.", new AcceptableValueRange<float>(0f, 80f)));
BatReverseSpeed = config.Bind(batform, "Reverse Speed", 8f,
new ConfigDescription("Speed while holding S, in m/s. Costs the powered stamina.", new AcceptableValueRange<float>(0f, 40f)));
BatLiftoffSpeed = config.Bind(batform, "Liftoff Speed", 9f,
new ConfigDescription("Climb speed out of water, in m/s. Always free, so a bat that touches the sea can still leave it.", new AcceptableValueRange<float>(0f, 30f)));
BatHoverSeconds = config.Bind(batform, "Hover Seconds", 3f,
new ConfigDescription("How long the bat holds its height after the last powered beat before it starts to glide down.", new AcceptableValueRange<float>(0f, 30f)));
BatPoweredStaminaPerSecond = config.Bind(batform, "Flight Stamina Per Second", 3f,
new ConfigDescription("Stamina per second while holding W or S. Out of stamina, the bat can only glide. 0 makes flight free, like the drake's.", new AcceptableValueRange<float>(0f, 60f)));
BatSprintStaminaPerSecond = config.Bind(batform, "Sprint Stamina Per Second", 12f,
new ConfigDescription("Extra stamina per second while sprinting, on top of the flight cost.", new AcceptableValueRange<float>(0f, 60f)));
BatEncumbered = config.Bind(batform, "While Encumbered", EncumberedMode.Allowed,
new ConfigDescription("Allowed: the bat flies while you carry too much, at the extra stamina cost below. Blocked: you cannot take bat form while encumbered, and a bat that becomes encumbered in the air can only glide down.", null));
BatEncumberedExtraCost = config.Bind(batform, "Encumbered Extra Stamina Cost", 0.15f,
new ConfigDescription("With 'Allowed' above: how much more flight and sprint cost while encumbered. 0.15 = 15% more.", new AcceptableValueRange<float>(0f, 1f)));
BatMaxDuration = config.Bind(batform, "Max Duration", 0f,
new ConfigDescription("Seconds the bat form lasts before you turn back on your own. 0 means no limit: stamina is the limit.", new AcceptableValueRange<float>(0f, 3600f)));
BatDurationPerState = config.Bind(batform, "Duration Per State", 0f,
new ConfigDescription("Seconds added to the max duration per progression state. Does nothing while the max duration is 0.", new AcceptableValueRange<float>(0f, 600f)));
BatCooldown = config.Bind(batform, "Cooldown", 0f,
new ConfigDescription("Seconds after leaving bat form before you can take it again. 0 means none.", new AcceptableValueRange<float>(0f, 3600f)));
const string aura = "Aswid - Vampiric Aura";
AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f,

View file

@ -598,6 +598,13 @@ namespace RacesOfValheim
{
bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false);
bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false);
// The bat flies on m_flying, which only the bat's own client sets. Mirror it here
// and switch gravity off for the duration, or this copy sinks to the terrain
// whatever altitude is replicated - the same fix ZdoVisualSync applies to drakes.
HarmonyLib.Traverse.Create(player).Field("m_flying").SetValue(isBat);
Rigidbody body = player.GetComponent<Rigidbody>();
if (body != null && body.useGravity == isBat) body.useGravity = !isBat;
Transform playerVisual = player.transform.Find("Visual");

View file

@ -674,9 +674,26 @@ namespace RacesOfValheim
return;
}
if (AswidConfig.BatEncumbered.Value == AswidConfig.EncumberedMode.Blocked && Player.m_localPlayer.IsEncumbered())
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_too_heavy_for_bat"));
return;
}
float cooldownLeft = AswidConfig.BatCooldown.Value - (Time.time - lastBatEndTime);
if (cooldownLeft > 0f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_cooldown", Mathf.CeilToInt(cooldownLeft)));
return;
}
RunFormRoutine(TransformIntoBatRoutine(rules));
}
// When the bat form last ended, for the optional cooldown. Starts far enough back that a
// fresh session never begins on cooldown.
private float lastBatEndTime = -100000f;
// The one bat or mist routine in flight, if any. Kept so ResetRace can stop it: a
// TransformIntoBatRoutine left running through a reset finishes its 1.1s gesture and
// turns a freshly reset Human into a bat.
@ -750,7 +767,7 @@ namespace RacesOfValheim
/// Update() has already bailed out on IsDead(), so a coroutine started here would be the
/// only thing still running on a corpse.
///
/// Leaving the form up costs more than a missing animation: m_debugFly stays on, so the
/// Leaving the form up costs more than a missing animation: m_flying stays on, so the
/// respawned player floats; Aswid_IsBatForm stays true in the ZDO, so every other client
/// keeps drawing a bat over a body that is walking around as a person; and the 5% scale
/// stays on the transform. Called from Aswid_BatDiesAsBat_Patch.
@ -776,12 +793,13 @@ namespace RacesOfValheim
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("Aswid_IsBatForm", false);
nview.GetZDO().Set(ZDOVars.s_debugFly, false);
}
Traverse.Create(player).Field("m_debugFly").SetValue(false);
// Now, not when the destroyed model's OnDestroy gets round to it at the end of the frame.
BatFormBehavior.SetFlying(false);
player.transform.localScale = Vector3.one;
lastBatEndTime = Time.time;
IsTransformed = false;
activeRules = null;
isTransformingSequence = false;
@ -881,6 +899,7 @@ namespace RacesOfValheim
}
Player.m_localPlayer.transform.localScale = endScale;
lastBatEndTime = Time.time;
IsTransformed = false;
activeRules = null;
isTransformingSequence = false;

View file

@ -1,86 +1,134 @@
using HarmonyLib;
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// The bat's flight, held on for as long as the worn model exists.
///
/// Debug fly has two halves, and this used to write only one. The field Player.m_debugFly is
/// what the local player's own physics reads; ZDOVars.s_debugFly is what every OTHER client
/// reads, because Character.IsDebugFlying consults the ZDO whenever it is not the owner. With
/// only the field written, a bat flew on its own screen and fell, walked and swam on everyone
/// else's - the fault WarVultureMount.SetFlying already names in its own summary. Both halves
/// go through SetFlying below now, so there is one place that can ever get it wrong again.
/// The bat flies on Character.m_flying and is steered by DirectedFlightPatch, the same
/// controls as the Skadi's drake; this class only hands over the bat's own numbers and keeps
/// the flag up. It used to fly on vanilla's debug-fly flag, which ignored carry weight, cost
/// nothing, moved at 50 m/s and made every monster blind to the player - the Discord reports
/// that started the 2026 rebalance.
///
/// Writing the ZDO every frame is not network spam: ZDO.Set(int, bool) bottoms out in
/// ZDOExtraData.Set, which returns false when the value is unchanged, and only a true return
/// bumps the data revision. Read out of the assembly rather than assumed, because "every frame"
/// deserved the check.
/// Other clients learn the bat is airborne from Aswid_IsBatForm in the ZDO, which
/// Aswid_MultiplayerVisuals_Patch mirrors into their copy's m_flying.
/// </summary>
public class BatFormBehavior : MonoBehaviour
public class BatFormBehavior : MonoBehaviour, IDirectedFlyer
{
private static readonly System.Reflection.FieldInfo DebugFlyField =
AccessTools.Field(typeof(Player), "m_debugFly");
private static readonly System.Reflection.FieldInfo FlyingField =
AccessTools.Field(typeof(Character), "m_flying");
private Animator anim;
private AswidProgression.FormRules formRules;
private float startTime;
private bool warnedTooHeavy;
private bool expired;
public void Initialize(AswidProgression.FormRules rules)
{
this.formRules = rules;
}
// ─── IDirectedFlyer ─────────────────────────────────────────────────────
// A bat is never grounded on purpose: it flies for as long as the form lasts.
public bool IsFlying => true;
public float LastPoweredTime { get; set; }
public float TurnSpeed => AswidConfig.BatTurnSpeed.Value;
public float GlideSpeed => AswidConfig.BatGlideSpeed.Value;
public float BoostSpeed => AswidConfig.BatBoostSpeed.Value;
public float SprintSpeed => AswidConfig.BatSprintSpeed.Value;
public float ReverseSpeed => AswidConfig.BatReverseSpeed.Value;
public float LiftoffSpeed => AswidConfig.BatLiftoffSpeed.Value;
public float HoverSeconds => AswidConfig.BatHoverSeconds.Value;
public float PoweredStaminaPerSecond => AswidConfig.BatPoweredStaminaPerSecond.Value * EncumberedCostFactor();
public float SprintStaminaPerSecond => AswidConfig.BatSprintStaminaPerSecond.Value * EncumberedCostFactor();
public bool CanPower => !(IsEncumbered() && AswidConfig.BatEncumbered.Value == AswidConfig.EncumberedMode.Blocked);
private static bool IsEncumbered()
{
return Player.m_localPlayer != null && Player.m_localPlayer.IsEncumbered();
}
private static float EncumberedCostFactor()
{
return IsEncumbered() ? 1f + AswidConfig.BatEncumberedExtraCost.Value : 1f;
}
/// <summary>
/// The form's lifetime in seconds at the current state, or 0 for no limit. The per-state
/// bonus is Dissolution's "scales with boss progression", and only means anything on top
/// of a base limit.
/// </summary>
public static float MaxDuration()
{
float max = AswidConfig.BatMaxDuration.Value;
if (max <= 0f) return 0f;
return max + AswidConfig.BatDurationPerState.Value * BossProgressionManager.GetCurrentProgressionState();
}
private void Start()
{
anim = GetComponentInChildren<Animator>();
startTime = Time.time;
LastPoweredTime = Time.time;
DirectedFlight.Register(this);
SetFlying(true);
}
private void Update()
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
Player player = Player.m_localPlayer;
if (player == null || player.IsDead()) return;
// Ensure flight remains on continuously
// Held every frame rather than set once, for the same reason the debug-fly flag was:
// anything that clears it mid-form (a vanilla reset, another mod) would drop the bat
// into walking with the model still on.
SetFlying(true);
// Sync Animator
if (!CanPower && !warnedTooHeavy)
{
warnedTooHeavy = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_too_heavy_to_beat"));
}
else if (CanPower)
{
warnedTooHeavy = false;
}
float max = MaxDuration();
if (max > 0f && !expired && Time.time - startTime >= max && AswidRace.Instance != null)
{
expired = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_form_fades"));
AswidRace.Instance.ForceRevert();
}
if (anim != null)
{
Vector3 vel = Player.m_localPlayer.GetVelocity();
Vector3 vel = player.GetVelocity();
vel.y = 0f;
float speed = vel.magnitude;
// Bats don't necessarily have a complex animator like players,
// but if they do have a speed or flying parameter, we set it here.
anim.SetFloat("forward_speed", speed);
anim.SetFloat("forward_speed", vel.magnitude);
anim.SetBool("flying", true);
}
}
private void OnDestroy()
{
DirectedFlight.Unregister(this);
SetFlying(false);
}
/// <summary>
/// Both halves of debug fly, always together. The field write survives a missing or invalid
/// ZNetView on purpose: without it a bat whose networking went away mid-flight would keep
/// flying on foot forever, which is the worse of the two failures.
/// The local half of flight. The remote half is the Aswid_IsBatForm ZDO flag AswidRace
/// already writes, so there is nothing to replicate here.
/// </summary>
private static void SetFlying(bool flying)
public static void SetFlying(bool flying)
{
Player player = Player.m_localPlayer;
if (player == null) return;
if (DebugFlyField != null) DebugFlyField.SetValue(player, flying);
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.IsOwner())
{
nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
}
if (player == null || FlyingField == null) return;
FlyingField.SetValue(player, flying);
}
}
}