Merge branch 'fix-trol-cave-workbench-destruction' into main

Same-faction mobs no longer smash player pieces - the truce previously
only covered combat hostility, not a mob's separate m_attackPlayerObjects
targeting.
This commit is contained in:
kanym 2026-08-09 17:12:52 +02:00
commit 4610c30279

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
@ -91,4 +92,44 @@ namespace RacesOfValheim
}
}
}
/// <summary>
/// The truce above only ever touches BaseAI.IsEnemy - a mob's decision to smash a nearby
/// piece runs on a completely separate track. MonsterAI.UpdateTarget gates that on
/// m_attackPlayerObjects (a flag baked into the prefab, true for Troll among others) and
/// never once calls IsEnemy: a Troll with nothing to fight picks a m_targetStatic and
/// swings at it regardless of who is standing next to it. That is how a Trol player,
/// exempt from that very Troll's hostility, could still watch it flatten a workbench built
/// two seconds earlier in its own cave.
///
/// A postfix on UpdateTarget rather than trying to intercept FindClosestStaticPriorityTarget
/// or FindRandomStaticTarget (both private, both called from more than one branch inside it):
/// simpler to let vanilla pick whatever it wants and veto the pick once, right after, than to
/// duplicate its target-selection logic to stop it picking in the first place.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateTarget")]
public static class FactionStaticTargetPatch
{
// Comfortably past FindRandomStaticTarget's own 10 m search radius, so a truce holds for
// any piece the mob could have picked in the first place.
private const float FactionCheckRange = 20f;
public static void Postfix(MonsterAI __instance)
{
Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic");
if (targetStatic.GetValue() == null) return;
Character monster = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (monster == null) return;
foreach (Player player in Player.GetAllPlayers())
{
if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue;
if (!FactionHostilityPatch.IsSameFaction(player, monster)) continue;
targetStatic.SetValue(null);
return;
}
}
}
}