diff --git a/JotunnModStub/Aswid/AswidBatAggro.cs b/JotunnModStub/Aswid/AswidBatAggro.cs
deleted file mode 100644
index 3bb4e6f..0000000
--- a/JotunnModStub/Aswid/AswidBatAggro.cs
+++ /dev/null
@@ -1,182 +0,0 @@
-using HarmonyLib;
-using UnityEngine;
-
-namespace RacesOfValheim
-{
- ///
- /// 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.
- ///
- public static class AswidBatForm
- {
- ///
- /// 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.
- ///
- 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--; }
-
- ///
- /// 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.
- ///
- public static bool IsBat(Player player)
- {
- if (player == null) return false;
-
- ZNetView nview = player.GetComponent();
- if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
-
- return player == Player.m_localPlayer &&
- player.GetSEMan() != null &&
- player.GetSEMan().HaveStatusEffect(BatFormHash);
- }
- }
-
- ///
- /// 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.
- ///
- [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;
- }
- }
-
- ///
- /// 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.
- ///
- [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;
- }
- }
-
- ///
- /// 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.
- ///
- [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();
- }
- }
-
- /// The networked half of the same thing: a hit sent by another machine.
- [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();
- }
- }
-
- ///
- /// 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.
- ///
- [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();
- }
- }
-
- ///
- /// 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.
- ///
- [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();
- }
- }
-}
diff --git a/JotunnModStub/Aswid/AswidBatFlight.cs b/JotunnModStub/Aswid/AswidBatFlight.cs
deleted file mode 100644
index e101fb7..0000000
--- a/JotunnModStub/Aswid/AswidBatFlight.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-using HarmonyLib;
-using UnityEngine;
-
-namespace RacesOfValheim
-{
- ///
- /// 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.
- ///
- [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;
- }
- }
-}
diff --git a/JotunnModStub/Aswid/AswidBatForm.cs b/JotunnModStub/Aswid/AswidBatForm.cs
new file mode 100644
index 0000000..dcf985b
--- /dev/null
+++ b/JotunnModStub/Aswid/AswidBatForm.cs
@@ -0,0 +1,59 @@
+using HarmonyLib;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// 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.
+ ///
+ public static class AswidBatForm
+ {
+ ///
+ /// The ZDO flag AswidRace writes when the form goes up. Replicated, so it answers for
+ /// remote players too.
+ ///
+ public const string BatZdoKey = "Aswid_IsBatForm";
+
+ private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
+
+ ///
+ /// 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.
+ ///
+ public static bool IsBat(Player player)
+ {
+ if (player == null) return false;
+
+ ZNetView nview = player.GetComponent();
+ if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(BatZdoKey, false)) return true;
+
+ return player == Player.m_localPlayer &&
+ player.GetSEMan() != null &&
+ player.GetSEMan().HaveStatusEffect(BatFormHash);
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ [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();
+ }
+ }
+}
diff --git a/JotunnModStub/Aswid/AswidConfig.cs b/JotunnModStub/Aswid/AswidConfig.cs
index dd9dbc5..c0e191b 100644
--- a/JotunnModStub/Aswid/AswidConfig.cs
+++ b/JotunnModStub/Aswid/AswidConfig.cs
@@ -42,12 +42,26 @@ namespace RacesOfValheim
public static ConfigEntry 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 BatFormAggro;
- public static ConfigEntry BatFormVulnerable;
- // A factor on vanilla's debug-fly speed, not a speed in metres - see AswidBatFlight.
- public static ConfigEntry 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 BatTurnSpeed;
+ public static ConfigEntry BatGlideSpeed;
+ public static ConfigEntry BatBoostSpeed;
+ public static ConfigEntry BatSprintSpeed;
+ public static ConfigEntry BatReverseSpeed;
+ public static ConfigEntry BatLiftoffSpeed;
+ public static ConfigEntry BatHoverSeconds;
+ public static ConfigEntry BatPoweredStaminaPerSecond;
+ public static ConfigEntry BatSprintStaminaPerSecond;
+ public static ConfigEntry BatEncumbered;
+ public static ConfigEntry BatEncumberedExtraCost;
+ public static ConfigEntry BatMaxDuration;
+ public static ConfigEntry BatDurationPerState;
+ public static ConfigEntry BatCooldown;
// ─── Vampiric Aura (passive, always active) ──────────────────────────────
public static ConfigEntry 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(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(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(30f, 720f)));
+ BatGlideSpeed = config.Bind(batform, "Glide Speed", 6f,
+ new ConfigDescription("Speed while gliding down with no key held, in m/s.", new AcceptableValueRange(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(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(0f, 80f)));
+ BatReverseSpeed = config.Bind(batform, "Reverse Speed", 8f,
+ new ConfigDescription("Speed while holding S, in m/s. Costs the powered stamina.", new AcceptableValueRange(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(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(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(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(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(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(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(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(0f, 3600f)));
const string aura = "Aswid - Vampiric Aura";
AuraTickInterval = config.Bind(aura, "Tick Interval", 0.25f,
diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs
index e413174..f823067 100644
--- a/JotunnModStub/Aswid/AswidPatches.cs
+++ b/JotunnModStub/Aswid/AswidPatches.cs
@@ -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();
+ if (body != null && body.useGravity == isBat) body.useGravity = !isBat;
Transform playerVisual = player.transform.Find("Visual");
diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs
index d96b68c..b93f730 100644
--- a/JotunnModStub/Aswid/AswidRace.cs
+++ b/JotunnModStub/Aswid/AswidRace.cs
@@ -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;
diff --git a/JotunnModStub/Aswid/BatFormBehavior.cs b/JotunnModStub/Aswid/BatFormBehavior.cs
index ef51ba2..75646d6 100644
--- a/JotunnModStub/Aswid/BatFormBehavior.cs
+++ b/JotunnModStub/Aswid/BatFormBehavior.cs
@@ -1,86 +1,134 @@
using HarmonyLib;
using UnityEngine;
-using Jotunn.Managers;
namespace RacesOfValheim
{
///
/// 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.
///
- 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ 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();
+ 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);
}
///
- /// 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.
///
- 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();
- if (nview != null && nview.IsValid() && nview.IsOwner())
- {
- nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
- }
+ if (player == null || FlyingField == null) return;
+ FlyingField.SetValue(player, flying);
}
}
}
diff --git a/JotunnModStub/DirectedFlight.cs b/JotunnModStub/DirectedFlight.cs
new file mode 100644
index 0000000..49d2b5d
--- /dev/null
+++ b/JotunnModStub/DirectedFlight.cs
@@ -0,0 +1,262 @@
+using System.Reflection;
+using HarmonyLib;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// A form that flies on Character's native flying-creature movement (m_flying) and is steered
+ /// by DirectedFlightPatch. The Skadi's drakes were the first; the Aswid's bat moved onto it from
+ /// vanilla's debug-fly flag in the 2026 rebalance, so the two share one set of controls and
+ /// differ only in the numbers each form hands back here.
+ ///
+ public interface IDirectedFlyer
+ {
+ /// False while the form is on the ground on purpose (a landed drake).
+ bool IsFlying { get; }
+
+ /// Time.time of the last powered or grounded moment; the hover window counts from it.
+ float LastPoweredTime { get; set; }
+
+ float TurnSpeed { get; }
+ float GlideSpeed { get; }
+ float BoostSpeed { get; }
+ float SprintSpeed { get; }
+ float ReverseSpeed { get; }
+ float LiftoffSpeed { get; }
+ float HoverSeconds { get; }
+
+ /// Stamina per second for powered flight (forward or reverse). 0 is free.
+ float PoweredStaminaPerSecond { get; }
+
+ /// Stamina per second for the sprint, charged on top of the powered cost.
+ float SprintStaminaPerSecond { get; }
+
+ /// False forbids powered flight outright, so the form can only glide and sink.
+ bool CanPower { get; }
+ }
+
+ public static class DirectedFlight
+ {
+ /// The local player's flying form, if any. Set and cleared by the form itself.
+ public static IDirectedFlyer Active { get; private set; }
+
+ public static void Register(IDirectedFlyer flyer) { Active = flyer; }
+
+ public static void Unregister(IDirectedFlyer flyer)
+ {
+ if (Active == flyer) Active = null;
+ }
+
+ /// The active form, only while it is actually in the air.
+ public static IDirectedFlyer Flying => Active != null && Active.IsFlying ? Active : null;
+ }
+
+ // The form flips the player into Character's native flying-creature movement (m_flying = true)
+ // instead of the debug-fly noclip, which lets us feed it a full 3D move direction.
+ // Character.UpdateFlying normally reads whatever m_moveDir the vanilla input pipeline last
+ // wrote (ground-plane WASD relative to camera yaw only); this patch overwrites it every frame
+ // with the camera's actual look direction (pitch included) so the player always glides toward
+ // wherever the mouse is aiming, with W powering forward, Shift spending stamina for a burst of
+ // speed, and S beating backwards away from whatever you are looking at.
+ [HarmonyPatch(typeof(Character), "UpdateFlying")]
+ public static class DirectedFlightPatch
+ {
+ // Tangent of the unpowered descent angle: 0.4 sinks at roughly 22 degrees below level.
+ private const float DESCENT_SLOPE = 0.4f;
+ // How much of the aim heading survives the climb out of water. Mostly up, with enough
+ // forward in it that the player still chooses which shore they surface towards.
+ private const float LIFTOFF_HEADING_BLEND = 0.35f;
+ // How far the left stick has to be pushed before it counts as W or S.
+ private const float StickThreshold = 0.5f;
+
+ ///
+ /// True while the local player is beating backwards this frame. Read by
+ /// SkadiReverseFacingPatch, which keeps the body pointed at the camera while it happens.
+ ///
+ public static bool Reversing { get; private set; }
+
+ // The September 2026 hotfix dropped the bool parameter from ZInput.GetJoyLeftStickY.
+ // A direct call binds to whichever signature we compiled against and throws
+ // MissingMethodException on the other, so resolve it at runtime and accept either.
+ private static readonly MethodInfo JoyLeftStickYMethod =
+ AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new System.Type[0]) ??
+ AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new[] { typeof(bool) });
+
+ private static float JoyLeftStickY()
+ {
+ if (JoyLeftStickYMethod == null) return 0f;
+ return (float)JoyLeftStickYMethod.Invoke(null, JoyLeftStickYArgs);
+ }
+
+ // Old signature: pass smooth = true, which was its default.
+ private static readonly object[] JoyLeftStickYArgs =
+ JoyLeftStickYMethod != null && JoyLeftStickYMethod.GetParameters().Length == 1 ? new object[] { true } : null;
+
+ public static void Prefix(Character __instance, float dt)
+ {
+ if (__instance != Player.m_localPlayer) return;
+
+ IDirectedFlyer form = DirectedFlight.Flying;
+ if (form == null)
+ {
+ Reversing = false;
+ return;
+ }
+
+ var traverse = Traverse.Create(__instance);
+ Vector3 lookDir = Player.m_localPlayer.GetLookDir();
+ bool input = RaceInput.Allowed;
+ // The pad's half of W/S: the left stick, read with vanilla's own sign -
+ // PlayerController.FixedUpdate takes forward as the NEGATED GetJoyLeftStickY.
+ // Flight only knows powered forward, reverse or neither, so the stick is a
+ // threshold, not a throttle. Steering stays on the camera, i.e. the right stick.
+ float stick = -JoyLeftStickY();
+ bool forward = input && (Input.GetKey(KeyCode.W) || stick > StickThreshold);
+ // Forward wins a W+S mash rather than the two cancelling into a dead hover.
+ bool backward = input && !forward && (Input.GetKey(KeyCode.S) || stick < -StickThreshold);
+ // Sprint on a pad is vanilla's run button, wherever the chosen layout puts it.
+ bool sprintKey = input && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) ||
+ ZInput.GetButton("JoyRun"));
+ bool onGround = __instance.IsOnGround();
+ // IsSwimming is the exact test UpdateMotion uses to hand the frame to UpdateSwimming
+ // instead of UpdateFlying, so it is also the one condition DirectedFlightWaterPatch has
+ // to take back. Its half-second tail past leaving the water is welcome here - it
+ // keeps the climb going just long enough to clear the surface properly.
+ bool inWater = __instance.IsSwimming();
+
+ // Powered flight is paid for up front, per frame. A form that cannot pay - out of
+ // stamina, or barred from powering at all - falls through to the glide below rather
+ // than out of the sky.
+ if ((forward || backward) && !(form.CanPower && TrySpendStamina(form.PoweredStaminaPerSecond, dt)))
+ {
+ forward = false;
+ backward = false;
+ }
+
+ Reversing = backward;
+
+ // m_run only picks between the two fly speeds. Every mode now has its own speed, so
+ // leave it off and drive all of them through m_flySlowSpeed.
+ traverse.Field("m_run").SetValue(false);
+
+ // UpdateFlying rotates the body toward m_moveDir on its own, but at m_flyTurnSpeed,
+ // which sits at Character's 12 deg/s default because the Player prefab was never set
+ // up as a flying creature - a 90 degree turn would take over seven seconds, so the
+ // model reads as not turning at all. Give it a speed that suits a flying form.
+ traverse.Field("m_flyTurnSpeed").SetValue(form.TurnSpeed);
+
+ // Powered flight, ground contact and clawing out of water all refresh the hover
+ // window, so none of them can be followed by an immediate sink.
+ if (forward || backward || onGround || inWater) form.LastPoweredTime = Time.time;
+
+ Vector3 moveDir = lookDir;
+ float speed;
+
+ if (inWater)
+ {
+ // Wet wings still beat. Water used to be a trap: UpdateMotion hands a swimming
+ // character to UpdateSwimming before it ever looks at m_flying, so a form that
+ // touched the sea was stuck paddling with the flight controls doing nothing.
+ // DirectedFlightWaterPatch gives the frame back to flight, and this branch spends
+ // it climbing regardless of where the camera points, so the surface is always
+ // something you break out of rather than something you sit in. Free on purpose:
+ // a form that could not pay to leave the water would drown in it.
+ moveDir = (Vector3.up + FlatHeading(__instance, lookDir) * LIFTOFF_HEADING_BLEND).normalized;
+ speed = form.LiftoffSpeed;
+ }
+ else if (backward)
+ {
+ // Straight reverse thrust along the aim, pitch included: look down and beat back
+ // and you rise away from what you are looking at, which is the whole point of
+ // having a reverse - you can retreat without taking your eyes (or your breath
+ // attack, which fires along the same vector) off the target.
+ moveDir = -lookDir;
+ speed = form.ReverseSpeed;
+ }
+ else if (forward)
+ {
+ speed = form.BoostSpeed;
+ if (sprintKey && TrySpendStamina(form.SprintStaminaPerSecond, dt)) speed = form.SprintSpeed;
+ }
+ else if (onGround || Time.time - form.LastPoweredTime < form.HoverSeconds)
+ {
+ // Holding station: on the ground this keeps a touchdown from sliding the player
+ // forward forever, and in the air it gives the beats of level flight before the
+ // form starts to sink. m_moveDir stays full length so the body still turns to
+ // face the camera, and zeroing the speed (rather than the rigidbody velocity)
+ // avoids fighting the AddForce UpdateFlying queues, which caused visible jitter.
+ speed = 0f;
+ }
+ else
+ {
+ // Unpowered flight is a glide, not a hover with a joystick: drift along the
+ // heading the camera faces while losing height, so aiming at the sky without
+ // holding W no longer climbs.
+ moveDir = (FlatHeading(__instance, lookDir) + Vector3.down * DESCENT_SLOPE).normalized;
+ speed = form.GlideSpeed;
+ }
+
+ traverse.Field("m_moveDir").SetValue(moveDir);
+ traverse.Field("m_flySlowSpeed").SetValue(speed);
+ }
+
+ /// Aim flattened onto the ground plane, falling back to the body's own facing
+ /// when the player is looking straight up or down.
+ private static Vector3 FlatHeading(Character character, Vector3 lookDir)
+ {
+ Vector3 heading = new Vector3(lookDir.x, 0f, lookDir.z);
+ if (heading.sqrMagnitude < 0.0001f)
+ {
+ heading = character.transform.forward;
+ heading.y = 0f;
+ }
+ return heading.normalized;
+ }
+
+ ///
+ /// Charges this frame of a per-second cost. Returns false when the player cannot pay.
+ /// A rate of zero is always paid, so a free mode costs nothing and never fails.
+ ///
+ private static bool TrySpendStamina(float perSecond, float dt)
+ {
+ if (perSecond <= 0f) return true;
+
+ Player player = Player.m_localPlayer;
+ if (player == null) return false;
+
+ float cost = perSecond * dt;
+ if (!player.HaveStamina(cost)) return false;
+
+ player.UseStamina(cost);
+ return true;
+ }
+ }
+
+ ///
+ /// Character.UpdateMotion asks IsSwimming before it asks m_flying, so a flying form that
+ /// touched water was handed to UpdateSwimming every frame: the flight patch above never ran,
+ /// the form paddled on the surface, and there was no way back into the air short of finding
+ /// land. Hand those frames back to UpdateFlying, which is the only motion path the two methods
+ /// contend over: nothing else calls either of them, and everything that merely asks
+ /// IsSwimming - the Wet status, the animator, stamina - is left alone.
+ ///
+ [HarmonyPatch(typeof(Character), "UpdateSwimming")]
+ public static class DirectedFlightWaterPatch
+ {
+ private static readonly MethodInfo UpdateFlyingMethod = AccessTools.Method(typeof(Character), "UpdateFlying");
+
+ public static bool Prefix(Character __instance, float dt)
+ {
+ if (__instance != Player.m_localPlayer) return true;
+ if (DirectedFlight.Flying == null) return true;
+
+ // Fail open: if a game update ever renames the method, swim normally rather than
+ // freezing the player in place with no motion update at all.
+ if (UpdateFlyingMethod == null) return true;
+
+ UpdateFlyingMethod.Invoke(__instance, new object[] { dt });
+ return false;
+ }
+ }
+}
diff --git a/JotunnModStub/Package/README.md b/JotunnModStub/Package/README.md
index a1ec2f4..30c6479 100644
--- a/JotunnModStub/Package/README.md
+++ b/JotunnModStub/Package/README.md
@@ -19,7 +19,7 @@ This mod currently introduces 4 custom races:
### 4. Aswid
- **The Vampire**: A creature of the night with powerful life-draining abilities.
-- **Bat Transformation**: Press `G` to transform into a bat, allowing you to fly over obstacles and travel quickly.
+- **Bat Transformation**: Press `G` to transform into a bat. It flies where you look, like the Skadi's drake: W beats forward, Shift sprints, S beats backwards, and both cost stamina. Out of stamina you can only glide.
- **Vampiric Aura**: Always on (toggle with [I]): drains the life of nearby enemies, with a doubled radius at night. Silent in Bat form until The Queen falls (configurable).
- **Blood Magic Mastery**: You can cast Blood Magic items with infinite Eitr, relying purely on their health costs.
- **Night Prowler**: Your passive speed and jump bonuses double during the night.
diff --git a/JotunnModStub/README.md b/JotunnModStub/README.md
index 85525ac..b549278 100644
--- a/JotunnModStub/README.md
+++ b/JotunnModStub/README.md
@@ -22,7 +22,7 @@ This mod currently introduces 6 custom races:
### 4. Aswid
- **The Vampire**: A creature of the night with powerful life-draining abilities.
-- **Bat Transformation**: Press G to transform into a bat, allowing you to fly over obstacles and travel quickly.
+- **Bat Transformation**: Press G to transform into a bat. It flies where you look, like the Skadi's drake: W beats forward, Shift sprints, S beats backwards, and both cost stamina. Out of stamina you can only glide.
- **Vampiric Aura**: Always on (toggle with [I]): drains the life of nearby enemies, with a doubled radius at night. Silent in Bat form until The Queen falls (configurable).
- **Blood Magic Mastery**: You can cast Blood Magic items with infinite Eitr, relying purely on their health costs.
- **Day walker, Night stalker**: Your passive speed and jump bonuses double during the night.
diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs
index 7b997fe..9855a42 100644
--- a/JotunnModStub/RaceCompendium.cs
+++ b/JotunnModStub/RaceCompendium.cs
@@ -491,7 +491,12 @@ namespace RacesOfValheim
sb.AppendLine(ModText.Get("rov_compendium_aswid_claws_beast_s_grows_blackened", (RaceClawsConfig.DurationSeconds.Value).ToString("0"), (SvermClaws.GetDamagePercent(state) * 100f).ToString("0")));
if (state >= 2)
+ {
sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_form_g_key_night"));
+ sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_flight",
+ AswidConfig.BatPoweredStaminaPerSecond.Value.ToString("0.#"),
+ AswidConfig.BatSprintStaminaPerSecond.Value.ToString("0.#")));
+ }
if (state >= 2)
sb.AppendLine(ModText.Get("rov_compendium_aswid_tame_u_key_tame_boar"));
diff --git a/JotunnModStub/Skadi/DrakeFormBehavior.cs b/JotunnModStub/Skadi/DrakeFormBehavior.cs
index b86a59e..331f6b9 100644
--- a/JotunnModStub/Skadi/DrakeFormBehavior.cs
+++ b/JotunnModStub/Skadi/DrakeFormBehavior.cs
@@ -4,10 +4,10 @@ using Jotunn.Managers;
namespace RacesOfValheim
{
- public class DrakeFormBehavior : MonoBehaviour
+ public class DrakeFormBehavior : MonoBehaviour, IDirectedFlyer
{
- // Single active instance, read by SkadiDirectedFlightPatch to feed a
- // look-direction-based m_moveDir into Character.UpdateFlying every frame.
+ // Single active instance, read by the Skadi patches that care about the drake itself
+ // (breath facing, attacks). Flight reads it through DirectedFlight.Active instead.
public static DrakeFormBehavior Active { get; private set; }
private Animator anim;
@@ -41,9 +41,25 @@ namespace RacesOfValheim
if (nview != null && nview.IsValid()) nview.GetZDO().Set(FlyingKey, value);
}
- // Time.time of the last powered/grounded moment. SkadiDirectedFlightPatch holds the form
+ // Time.time of the last powered/grounded moment. DirectedFlightPatch holds the form
// level for a short window past this before letting it start sinking.
- public float LastPoweredTime;
+ public float LastPoweredTime { get; set; }
+
+ // The drake's numbers for DirectedFlightPatch. Base flight stays free on purpose - the
+ // drake arrives at the Elder, long before the player has the stamina pool to pay for
+ // simply staying airborne - so only the sprint costs anything.
+ public float TurnSpeed => SkadiConfig.FlightTurnSpeed.Value;
+ public float GlideSpeed => SkadiConfig.FlightGlideSpeed.Value;
+ public float BoostSpeed => SkadiConfig.FlightBoostSpeed.Value;
+ public float SprintSpeed => SkadiConfig.FlightSprintSpeed.Value;
+ public float ReverseSpeed => SkadiConfig.FlightReverseSpeed.Value;
+ // Climbing out of water is deliberately slower than a powered climb in open air - the
+ // wings are dragging themselves free, not racing.
+ public float LiftoffSpeed => SkadiConfig.FlightLiftoffSpeed.Value;
+ public float HoverSeconds => SkadiConfig.FlightHoverSeconds.Value;
+ public float PoweredStaminaPerSecond => 0f;
+ public float SprintStaminaPerSecond => SkadiConfig.FlightSprintStaminaPerSecond.Value;
+ public bool CanPower => true;
private SkadiProgression.FormRules formRules;
@@ -97,6 +113,7 @@ namespace RacesOfValheim
private void Start()
{
Active = this;
+ DirectedFlight.Register(this);
anim = GetComponentInChildren();
if (Player.m_localPlayer != null)
@@ -609,6 +626,7 @@ namespace RacesOfValheim
private void OnDestroy()
{
if (Active == this) Active = null;
+ DirectedFlight.Unregister(this);
if (Player.m_localPlayer != null)
{
SetFlying(false);
diff --git a/JotunnModStub/Skadi/SkadiPatches.cs b/JotunnModStub/Skadi/SkadiPatches.cs
index a2aecb0..94b1c56 100644
--- a/JotunnModStub/Skadi/SkadiPatches.cs
+++ b/JotunnModStub/Skadi/SkadiPatches.cs
@@ -316,221 +316,7 @@ namespace RacesOfValheim
- // DrakeFormBehavior flips the player into Character's native flying-creature movement
- // (m_flying = true) instead of the old debug-fly noclip, which lets us feed it a full 3D
- // move direction. Character.UpdateFlying normally reads whatever m_moveDir the vanilla input
- // pipeline last wrote (ground-plane WASD relative to camera yaw only); this patch overwrites
- // it every frame with the camera's actual look direction (pitch included) so the player always
- // glides toward wherever the mouse is aiming, with W powering forward, Shift spending stamina
- // for a burst of speed, and S beating backwards away from whatever you are looking at.
- [HarmonyPatch(typeof(Character), "UpdateFlying")]
- public static class SkadiDirectedFlightPatch
- {
- // Read from SkadiConfig (BepInEx Config) rather than fixed constants, so flight can be
- // retuned from Configuration Manager - see CONFIGURATION-MANAGER-HOWTO.md.
- private static float TURN_SPEED => SkadiConfig.FlightTurnSpeed.Value;
- private static float GLIDE_SPEED => SkadiConfig.FlightGlideSpeed.Value;
- private static float BOOST_SPEED => SkadiConfig.FlightBoostSpeed.Value;
- private static float SPRINT_SPEED => SkadiConfig.FlightSprintSpeed.Value;
- private static float REVERSE_SPEED => SkadiConfig.FlightReverseSpeed.Value;
- // Climbing out of water is deliberately slower than a powered climb in open air - the
- // wings are dragging themselves free, not racing.
- private static float LIFTOFF_SPEED => SkadiConfig.FlightLiftoffSpeed.Value;
- private static float HOVER_SECONDS => SkadiConfig.FlightHoverSeconds.Value;
- // Per second, drained only while the sprint is actually being granted.
- private static float SPRINT_STAMINA_PER_SECOND => SkadiConfig.FlightSprintStaminaPerSecond.Value;
- // Tangent of the unpowered descent angle: 0.4 sinks at roughly 22 degrees below level.
- private const float DESCENT_SLOPE = 0.4f;
- // How much of the aim heading survives the climb out of water. Mostly up, with enough
- // forward in it that the player still chooses which shore they surface towards.
- private const float LIFTOFF_HEADING_BLEND = 0.35f;
- // How far the left stick has to be pushed before it counts as W or S.
- private const float StickThreshold = 0.5f;
-
- ///
- /// True while the local player is beating backwards this frame. Read by
- /// SkadiReverseFacingPatch, which keeps the body pointed at the camera while it happens.
- ///
- public static bool Reversing { get; private set; }
-
- // The September 2026 hotfix dropped the bool parameter from ZInput.GetJoyLeftStickY.
- // A direct call binds to whichever signature we compiled against and throws
- // MissingMethodException on the other, so resolve it at runtime and accept either.
- private static readonly MethodInfo JoyLeftStickYMethod =
- AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new System.Type[0]) ??
- AccessTools.Method(typeof(ZInput), "GetJoyLeftStickY", new[] { typeof(bool) });
-
- private static float JoyLeftStickY()
- {
- if (JoyLeftStickYMethod == null) return 0f;
- return (float)JoyLeftStickYMethod.Invoke(null, JoyLeftStickYArgs);
- }
-
- // Old signature: pass smooth = true, which was its default.
- private static readonly object[] JoyLeftStickYArgs =
- JoyLeftStickYMethod != null && JoyLeftStickYMethod.GetParameters().Length == 1 ? new object[] { true } : null;
-
- public static void Prefix(Character __instance, float dt)
- {
- if (__instance != Player.m_localPlayer) return;
-
- DrakeFormBehavior form = DrakeFormBehavior.Active;
- if (form == null || !form.IsFlying)
- {
- Reversing = false;
- return;
- }
-
- var traverse = Traverse.Create(__instance);
- Vector3 lookDir = Player.m_localPlayer.GetLookDir();
- bool input = RaceInput.Allowed;
- // The pad's half of W/S: the left stick, read with vanilla's own sign -
- // PlayerController.FixedUpdate takes forward as the NEGATED GetJoyLeftStickY.
- // Flight only knows powered forward, reverse or neither, so the stick is a
- // threshold, not a throttle. Steering stays on the camera, i.e. the right stick.
- float stick = -JoyLeftStickY();
- bool forward = input && (Input.GetKey(KeyCode.W) || stick > StickThreshold);
- // Forward wins a W+S mash rather than the two cancelling into a dead hover.
- bool backward = input && !forward && (Input.GetKey(KeyCode.S) || stick < -StickThreshold);
- // Sprint on a pad is vanilla's run button, wherever the chosen layout puts it.
- bool sprintKey = input && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift) ||
- ZInput.GetButton("JoyRun"));
- bool onGround = __instance.IsOnGround();
- // IsSwimming is the exact test UpdateMotion uses to hand the frame to UpdateSwimming
- // instead of UpdateFlying, so it is also the one condition SkadiWaterFlightPatch has
- // to take back. Its half-second tail past leaving the water is welcome here - it
- // keeps the climb going just long enough to clear the surface properly.
- bool inWater = __instance.IsSwimming();
-
- Reversing = backward;
-
- // m_run only picks between the two fly speeds. Every mode now has its own speed, so
- // leave it off and drive all of them through m_flySlowSpeed.
- traverse.Field("m_run").SetValue(false);
-
- // UpdateFlying rotates the body toward m_moveDir on its own, but at m_flyTurnSpeed,
- // which sits at Character's 12 deg/s default because the Player prefab was never set
- // up as a flying creature - a 90 degree turn would take over seven seconds, so the
- // model reads as not turning at all. Give it a speed that suits a flying mount.
- traverse.Field("m_flyTurnSpeed").SetValue(TURN_SPEED);
-
- // Powered flight, ground contact and clawing out of water all refresh the hover
- // window, so none of them can be followed by an immediate sink.
- if (forward || backward || onGround || inWater) form.LastPoweredTime = Time.time;
-
- Vector3 moveDir = lookDir;
- float speed;
-
- if (inWater)
- {
- // Wet wings still beat. Water used to be a trap: UpdateMotion hands a swimming
- // character to UpdateSwimming before it ever looks at m_flying, so a dragon that
- // touched the sea was stuck paddling with the flight controls doing nothing.
- // SkadiWaterFlightPatch gives the frame back to flight, and this branch spends it
- // climbing regardless of where the camera points, so the surface is always
- // something you break out of rather than something you sit in.
- moveDir = (Vector3.up + FlatHeading(__instance, lookDir) * LIFTOFF_HEADING_BLEND).normalized;
- speed = LIFTOFF_SPEED;
- }
- else if (backward)
- {
- // Straight reverse thrust along the aim, pitch included: look down and beat back
- // and you rise away from what you are looking at, which is the whole point of
- // having a reverse - you can retreat without taking your eyes (or your breath
- // attack, which fires along the same vector) off the target.
- moveDir = -lookDir;
- speed = REVERSE_SPEED;
- }
- else if (forward)
- {
- speed = BOOST_SPEED;
- // The sprint is the only part of flight that costs anything. Base flight stays
- // free on purpose - the drake arrives at the Elder, long before the player has
- // the stamina pool to pay for simply staying airborne.
- if (sprintKey && TrySpendSprintStamina(dt)) speed = SPRINT_SPEED;
- }
- else if (onGround || Time.time - form.LastPoweredTime < HOVER_SECONDS)
- {
- // Holding station: on the ground this keeps a touchdown from sliding the player
- // forward forever, and in the air it gives the beats of level flight before the
- // form starts to sink. m_moveDir stays full length so the body still turns to
- // face the camera, and zeroing the speed (rather than the rigidbody velocity)
- // avoids fighting the AddForce UpdateFlying queues, which caused visible jitter.
- speed = 0f;
- }
- else
- {
- // Unpowered flight is a glide, not a hover with a joystick: drift along the
- // heading the camera faces while losing height, so aiming at the sky without
- // holding W no longer climbs.
- moveDir = (FlatHeading(__instance, lookDir) + Vector3.down * DESCENT_SLOPE).normalized;
- speed = GLIDE_SPEED;
- }
-
- traverse.Field("m_moveDir").SetValue(moveDir);
- traverse.Field("m_flySlowSpeed").SetValue(speed);
- }
-
- /// Aim flattened onto the ground plane, falling back to the body's own facing
- /// when the player is looking straight up or down.
- private static Vector3 FlatHeading(Character character, Vector3 lookDir)
- {
- Vector3 heading = new Vector3(lookDir.x, 0f, lookDir.z);
- if (heading.sqrMagnitude < 0.0001f)
- {
- heading = character.transform.forward;
- heading.y = 0f;
- }
- return heading.normalized;
- }
-
- ///
- /// Charges this frame of sprint. Returns false when the player cannot pay, which drops
- /// them back to the free boost speed rather than out of the sky.
- ///
- private static bool TrySpendSprintStamina(float dt)
- {
- Player player = Player.m_localPlayer;
- if (player == null) return false;
-
- float cost = SPRINT_STAMINA_PER_SECOND * dt;
- if (!player.HaveStamina(cost)) return false;
-
- player.UseStamina(cost);
- return true;
- }
- }
-
- ///
- /// Character.UpdateMotion asks IsSwimming before it asks m_flying, so a flying dragon that
- /// touched water was handed to UpdateSwimming every frame: the flight patch above never ran,
- /// the form paddled on the surface, and there was no way back into the air short of finding
- /// land. (The Aswid's bat escapes this because debug-fly is checked at the very top of
- /// UpdateMotion, before water is considered at all - which is exactly why it can take off
- /// from the sea.) Hand those frames back to UpdateFlying, which is the only motion path the
- /// two methods contend over: nothing else calls either of them, and everything that merely
- /// asks IsSwimming - the Wet status, the animator, stamina - is left alone.
- ///
- [HarmonyPatch(typeof(Character), "UpdateSwimming")]
- public static class SkadiWaterFlightPatch
- {
- private static readonly MethodInfo UpdateFlyingMethod = AccessTools.Method(typeof(Character), "UpdateFlying");
-
- public static bool Prefix(Character __instance, float dt)
- {
- if (__instance != Player.m_localPlayer) return true;
-
- DrakeFormBehavior form = DrakeFormBehavior.Active;
- if (form == null || !form.IsFlying) return true;
-
- // Fail open: if a game update ever renames the method, swim normally rather than
- // freezing the player in place with no motion update at all.
- if (UpdateFlyingMethod == null) return true;
-
- UpdateFlyingMethod.Invoke(__instance, new object[] { dt });
- return false;
- }
- }
+ // Directed flight (the controls) lives in DirectedFlight.cs, shared with the Aswid's bat.
///
/// UpdateFlying turns the body to face m_moveDir, which is right for every direction of
@@ -559,10 +345,8 @@ namespace RacesOfValheim
return false;
}
- if (!SkadiDirectedFlightPatch.Reversing) return true;
-
- DrakeFormBehavior form = DrakeFormBehavior.Active;
- if (form == null || !form.IsFlying) return true;
+ if (!DirectedFlightPatch.Reversing) return true;
+ if (DirectedFlight.Flying == null) return true;
__result = true;
return false;
diff --git a/JotunnModStub/Translations/English/compendium.json b/JotunnModStub/Translations/English/compendium.json
index b4e1288..92d6fab 100644
--- a/JotunnModStub/Translations/English/compendium.json
+++ b/JotunnModStub/Translations/English/compendium.json
@@ -30,6 +30,7 @@
"rov_compendium_aswid_asmund_passive": "[Fader Unlock] Asmund (Passive):",
"rov_compendium_aswid_aswid_s_curse": "The Aswid's Curse\n",
"rov_compendium_aswid_bat_form_g_key_night": "[Eikthyr Unlock] Bat Form ('G' Key, night only): Take the shape of a bat.\n",
+ "rov_compendium_aswid_bat_flight": "The bat flies where you look: W beats forward for $1 stamina a second, Shift sprints for $2 more, S beats backwards, and letting go holds you still for a moment before you glide down. Out of stamina, you can only glide.\n",
"rov_compendium_aswid_bat_form_now_answers_by": "[The Elder Unlock] Bat Form now answers by day as well as night.\n",
"rov_compendium_aswid_benedictus_et_afflictus": "[Base Passive] Benedictus et Afflictus:",
"rov_compendium_aswid_claws_beast_s_grows_blackened": "[Base Passive] Claws of the Beast ([K], $1s): Grows blackened claws for a limited time instead of a weapon. Bare-handed blows land at $2% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in bat or mist form you have no hands to hold them with.\n",
diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json
index f658228..c6c484c 100644
--- a/JotunnModStub/Translations/English/messages.json
+++ b/JotunnModStub/Translations/English/messages.json
@@ -17,6 +17,10 @@
"rov_msg_aswid_tamed": "Tamed!",
"rov_msg_aswid_vae_victis": "Vae Victis",
"rov_msg_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse",
+ "rov_msg_aswid_bat_cooldown": "Your blood is not ready to take wing again ($1s)",
+ "rov_msg_aswid_bat_form_fades": "The bat form fades",
+ "rov_msg_aswid_bat_too_heavy_to_beat": "Too heavy to beat your wings. You can only glide",
+ "rov_msg_aswid_too_heavy_for_bat": "You carry too much to take bat form",
"rov_msg_build_limit_cooktable": "Another cook's table stands within forty paces. One cook to a yard.",
"rov_msg_build_limit_draugh_bodypile": "The ground here already carries $1 of these. Find another country.",
"rov_msg_build_limit_dvergar_contractbank": "There is already $1 contract bank within a day's walk. One ledger per valley.",
diff --git a/JotunnModStub/Translations/Italian/compendium.json b/JotunnModStub/Translations/Italian/compendium.json
index 9f1627a..e5191c9 100644
--- a/JotunnModStub/Translations/Italian/compendium.json
+++ b/JotunnModStub/Translations/Italian/compendium.json
@@ -30,6 +30,7 @@
"rov_compendium_aswid_asmund_passive": "[Sblocco Fader] Asmund (passiva):",
"rov_compendium_aswid_aswid_s_curse": "La maledizione degli Aswid\n",
"rov_compendium_aswid_bat_form_g_key_night": "[Sblocco Eikthyr] Forma di pipistrello (tasto 'G', solo di notte): prendi la forma di un pipistrello.\n",
+ "rov_compendium_aswid_bat_flight": "Il pipistrello vola dove guardi: W batte le ali in avanti per $1 stamina al secondo, Shift scatta per altri $2, S batte all'indietro, e se lasci tutto resti fermo un attimo prima di planare giù. Senza stamina puoi solo planare.\n",
"rov_compendium_aswid_bat_form_now_answers_by": "[Sblocco Antico] La forma di pipistrello ora risponde di giorno come di notte.\n",
"rov_compendium_aswid_benedictus_et_afflictus": "[Passiva base] Benedictus et Afflictus:",
"rov_compendium_aswid_claws_beast_s_grows_blackened": "[Passiva base] Artigli della Bestia ([K], $1s): per un tempo limitato fai crescere artigli anneriti al posto di un'arma. I colpi a mani nude valgono il $2% del peso di un paio adulto, tutto come danno da taglio, e crescono con ogni boss che cade. Sfodera una spada e aspettano, rinfoderala e tornano, finché il tempo non scade e si ritraggono da soli, senza sprecare uno slot tra un uso e l'altro. Mentre sono fuori non possono essere lasciati cadere, scambiati o rubati, e in forma di pipistrello o di nebbia non hai mani per tenerli.\n",
diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json
index 3293090..5b18030 100644
--- a/JotunnModStub/Translations/Italian/messages.json
+++ b/JotunnModStub/Translations/Italian/messages.json
@@ -17,6 +17,10 @@
"rov_msg_aswid_tamed": "Addomesticato!",
"rov_msg_aswid_vae_victis": "Vae Victis",
"rov_msg_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse",
+ "rov_msg_aswid_bat_cooldown": "Il tuo sangue non è pronto a spiccare il volo di nuovo ($1s)",
+ "rov_msg_aswid_bat_form_fades": "La forma di pipistrello svanisce",
+ "rov_msg_aswid_bat_too_heavy_to_beat": "Troppo pesante per battere le ali. Puoi solo planare",
+ "rov_msg_aswid_too_heavy_for_bat": "Porti troppo peso per prendere la forma di pipistrello",
"rov_msg_build_limit_cooktable": "C'è già un altro tavolo del cuoco entro quaranta passi. Un cuoco per cortile.",
"rov_msg_build_limit_draugh_bodypile": "Questo terreno ne porta già $1. Trova un'altra contrada.",
"rov_msg_build_limit_dvergar_contractbank": "C'è già $1 banca dei contratti a una giornata di cammino. Un registro per valle.",
diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json
index d56ec08..a650acb 100644
--- a/JotunnModStub/Translations/Russian/compendium.json
+++ b/JotunnModStub/Translations/Russian/compendium.json
@@ -30,6 +30,7 @@
"rov_compendium_aswid_asmund_passive": "[Награда: Прародитель] Асмунд (Пассивное):",
"rov_compendium_aswid_aswid_s_curse": "Проклятие Асвида\n",
"rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик летучей мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n",
+ "rov_compendium_aswid_bat_flight": "Летучая мышь летит туда, куда вы смотрите: W — полет вперед за $1 выносливости в секунду, Shift — рывок еще за $2, S — полет назад, а если отпустить клавиши, вы ненадолго зависаете, а затем планируете вниз. Без выносливости можно только планировать.\n",
"rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик летучей мыши теперь доступен как ночью, так и днем.\n",
"rov_compendium_aswid_benedictus_et_afflictus": "[Базовое пассивное] Benedictus et Afflictus:",
"rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике летучей мыши или тумана когти недоступны, так как у вас нет рук.\n",
diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json
index cd919e3..433b7c6 100644
--- a/JotunnModStub/Translations/Russian/messages.json
+++ b/JotunnModStub/Translations/Russian/messages.json
@@ -17,6 +17,10 @@
"rov_msg_aswid_tamed": "Приручено!",
"rov_msg_aswid_vae_victis": "Vae Victis",
"rov_msg_aswid_what_horrible_night_have_curse": "Какая ужасная ночь для носителя проклятия...",
+ "rov_msg_aswid_bat_cooldown": "Ваша кровь еще не готова снова подняться в небо ($1 с)",
+ "rov_msg_aswid_bat_form_fades": "Облик летучей мыши рассеивается",
+ "rov_msg_aswid_bat_too_heavy_to_beat": "Слишком тяжело, чтобы махать крыльями. Вы можете только планировать",
+ "rov_msg_aswid_too_heavy_for_bat": "Вы несете слишком много, чтобы принять облик летучей мыши",
"rov_msg_build_limit_cooktable": "В пределах сорока шагов уже стоит стол повара. Один повар на двор.",
"rov_msg_build_limit_draugh_bodypile": "Здешняя земля уже несет на себе $1 таких построек. Найдите другое место.",
"rov_msg_build_limit_dvergar_contractbank": "В радиусе дневного перехода уже есть $1 контрактная контора. Один гроссбух на долину.",