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

@ -0,0 +1,262 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public interface IDirectedFlyer
{
/// <summary>False while the form is on the ground on purpose (a landed drake).</summary>
bool IsFlying { get; }
/// <summary>Time.time of the last powered or grounded moment; the hover window counts from it.</summary>
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; }
/// <summary>Stamina per second for powered flight (forward or reverse). 0 is free.</summary>
float PoweredStaminaPerSecond { get; }
/// <summary>Stamina per second for the sprint, charged on top of the powered cost.</summary>
float SprintStaminaPerSecond { get; }
/// <summary>False forbids powered flight outright, so the form can only glide and sink.</summary>
bool CanPower { get; }
}
public static class DirectedFlight
{
/// <summary>The local player's flying form, if any. Set and cleared by the form itself.</summary>
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;
}
/// <summary>The active form, only while it is actually in the air.</summary>
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;
/// <summary>
/// True while the local player is beating backwards this frame. Read by
/// SkadiReverseFacingPatch, which keeps the body pointed at the camera while it happens.
/// </summary>
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);
}
/// <summary>Aim flattened onto the ground plane, falling back to the body's own facing
/// when the player is looking straight up or down.</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
/// <summary>
/// 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.
/// </summary>
[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;
}
}
}