环形轰炸,区域监视,光矛扫射

This commit is contained in:
2025-11-10 11:57:16 +08:00
parent 11c58f1b39
commit 97a1cbcf77
19 changed files with 2360 additions and 2 deletions

View File

@@ -0,0 +1,361 @@
using RimWorld;
using Verse;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
namespace WulaFallenEmpire
{
public class CompBuildingEnergyLance : ThingComp
{
public CompProperties_BuildingEnergyLance Props => (CompProperties_BuildingEnergyLance)props;
// 状态管理
private EnergyLanceState currentState = EnergyLanceState.Idle;
private int nextUpdateTick = 0;
private int noTargetTicks = 0;
// 目标管理
private Pawn currentTarget = null;
private IntVec3 lastTargetPosition = IntVec3.Invalid;
// EnergyLance实例
private GuidedEnergyLance activeLance = null;
public override void PostSpawnSetup(bool respawningAfterLoad)
{
base.PostSpawnSetup(respawningAfterLoad);
if (!respawningAfterLoad)
{
// 新生成时立即开始搜索目标
nextUpdateTick = Find.TickManager.TicksGame;
currentState = EnergyLanceState.Searching;
Log.Message($"[BuildingEnergyLance] Building spawned, starting target search");
}
}
private void UpdateState()
{
switch (currentState)
{
case EnergyLanceState.Idle:
// 空闲状态,等待下一次更新
break;
case EnergyLanceState.Searching:
SearchForTarget();
break;
case EnergyLanceState.Tracking:
TrackTarget();
break;
case EnergyLanceState.NoTarget:
HandleNoTarget();
break;
}
}
private void SearchForTarget()
{
Map map = parent.Map;
if (map == null) return;
// 获取范围内的所有有效目标
var potentialTargets = new List<Pawn>();
foreach (var pawn in map.mapPawns.AllPawnsSpawned)
{
if (IsValidTarget(pawn) && IsInRange(pawn.Position))
{
potentialTargets.Add(pawn);
}
}
if (potentialTargets.Count > 0)
{
// 选择第一个目标(可以改为其他选择逻辑)
currentTarget = potentialTargets[0];
lastTargetPosition = currentTarget.Position;
// 创建EnergyLance
CreateEnergyLance();
currentState = EnergyLanceState.Tracking;
noTargetTicks = 0;
Log.Message($"[BuildingEnergyLance] Locked target: {currentTarget.Label}, position: {currentTarget.Position}");
}
else
{
// 没有找到目标
currentState = EnergyLanceState.NoTarget;
Log.Message($"[BuildingEnergyLance] No targets found in range");
}
}
private void TrackTarget()
{
if (currentTarget == null || !currentTarget.Spawned)
{
// 目标丢失,重新搜索
currentState = EnergyLanceState.Searching;
currentTarget = null;
return;
}
// 检查目标是否仍然有效
if (!IsValidTarget(currentTarget) || !IsInRange(currentTarget.Position))
{
// 目标无效或超出范围,寻找最近的敌人
FindNearestTarget();
return;
}
// 更新目标位置
lastTargetPosition = currentTarget.Position;
// 向EnergyLance发送目标位置
if (activeLance != null && !activeLance.Destroyed)
{
activeLance.UpdateTarget(lastTargetPosition);
noTargetTicks = 0;
Log.Message($"[BuildingEnergyLance] Updated target position: {lastTargetPosition}");
}
else
{
// EnergyLance丢失重新创建
CreateEnergyLance();
}
}
private void FindNearestTarget()
{
Map map = parent.Map;
if (map == null) return;
Pawn nearestTarget = null;
float nearestDistance = float.MaxValue;
// 获取当前EnergyLance位置
IntVec3 searchCenter = (activeLance != null && !activeLance.Destroyed) ?
activeLance.Position : parent.Position;
foreach (var pawn in map.mapPawns.AllPawnsSpawned)
{
if (IsValidTarget(pawn) && IsInRange(pawn.Position))
{
float distance = Vector3.Distance(searchCenter.ToVector3(), pawn.Position.ToVector3());
if (distance < nearestDistance)
{
nearestDistance = distance;
nearestTarget = pawn;
}
}
}
if (nearestTarget != null)
{
currentTarget = nearestTarget;
lastTargetPosition = currentTarget.Position;
// 更新EnergyLance目标
if (activeLance != null && !activeLance.Destroyed)
{
activeLance.UpdateTarget(lastTargetPosition);
}
Log.Message($"[BuildingEnergyLance] Switched to nearest target: {currentTarget.Label}, distance: {nearestDistance}");
}
else
{
// 没有找到替代目标
currentState = EnergyLanceState.NoTarget;
currentTarget = null;
Log.Message($"[BuildingEnergyLance] No alternative targets found");
}
}
private void HandleNoTarget()
{
noTargetTicks++;
// 向EnergyLance发送空位置
if (activeLance != null && !activeLance.Destroyed)
{
activeLance.UpdateTarget(IntVec3.Invalid);
}
// 检查是否应该销毁EnergyLance
if (noTargetTicks >= Props.maxNoTargetTicks)
{
if (activeLance != null && !activeLance.Destroyed)
{
activeLance.Destroy();
activeLance = null;
}
// 回到搜索状态
currentState = EnergyLanceState.Searching;
noTargetTicks = 0;
Log.Message($"[BuildingEnergyLance] EnergyLance destroyed due to no targets");
}
else if (noTargetTicks % 60 == 0) // 每60刻检查一次是否有新目标
{
SearchForTarget();
}
}
private void CreateEnergyLance()
{
if (Props.energyLanceDef == null)
{
Log.Error($"[BuildingEnergyLance] No energyLanceDef configured");
return;
}
try
{
// 销毁现有的EnergyLance
if (activeLance != null && !activeLance.Destroyed)
{
activeLance.Destroy();
}
// 创建新的EnergyLance
IntVec3 spawnPos = GetLanceSpawnPosition();
activeLance = (GuidedEnergyLance)GenSpawn.Spawn(Props.energyLanceDef, spawnPos, parent.Map);
// 初始化EnergyLance
activeLance.duration = Props.energyLanceDuration;
activeLance.instigator = parent;
activeLance.controlBuilding = this.parent;
activeLance.firesPerTick = Props.firesPerTick;
// 如果有当前目标,设置初始位置
if (currentTarget != null)
{
activeLance.UpdateTarget(currentTarget.Position);
}
activeLance.StartStrike();
Log.Message($"[BuildingEnergyLance] Created EnergyLance at {spawnPos}");
}
catch (System.Exception ex)
{
Log.Error($"[BuildingEnergyLance] Error creating EnergyLance: {ex}");
}
}
private IntVec3 GetLanceSpawnPosition()
{
// 在建筑周围寻找一个合适的生成位置
Map map = parent.Map;
IntVec3 center = parent.Position;
// 优先选择建筑上方的位置
if (center.InBounds(map) && center.Walkable(map))
{
return center;
}
// 如果建筑位置不可用,在周围寻找
foreach (IntVec3 cell in GenRadial.RadialCellsAround(center, 2f, true))
{
if (cell.InBounds(map) && cell.Walkable(map))
{
return cell;
}
}
// 如果都不可用,返回建筑位置
return center;
}
private bool IsValidTarget(Pawn pawn)
{
if (pawn == null || pawn.Downed || pawn.Dead || !pawn.Spawned)
return false;
// 检查目标类型
if (Props.targetEnemies && pawn.HostileTo(parent.Faction))
return true;
if (Props.targetNeutrals && !pawn.HostileTo(parent.Faction) && pawn.Faction != parent.Faction)
return true;
if (Props.targetAnimals && pawn.RaceProps.Animal)
return true;
return false;
}
private bool IsInRange(IntVec3 position)
{
float distance = Vector3.Distance(parent.Position.ToVector3(), position.ToVector3());
return distance <= Props.radius;
}
public override void CompTick()
{
base.CompTick();
int currentTick = Find.TickManager.TicksGame;
// 检查是否需要更新状态
if (currentTick >= nextUpdateTick)
{
UpdateState();
nextUpdateTick = currentTick + Props.updateIntervalTicks;
}
// 检查EnergyLance状态
if (activeLance != null && activeLance.Destroyed)
{
activeLance = null;
if (currentState == EnergyLanceState.Tracking)
{
currentState = EnergyLanceState.Searching;
}
}
}
// 外部调用当EnergyLance需要目标时调用
public bool TryGetCurrentTarget(out IntVec3 targetPos)
{
if (currentTarget != null && IsValidTarget(currentTarget) && IsInRange(currentTarget.Position))
{
targetPos = currentTarget.Position;
return true;
}
targetPos = IntVec3.Invalid;
return false;
}
public override void PostExposeData()
{
base.PostExposeData();
Scribe_Values.Look(ref currentState, "currentState", EnergyLanceState.Idle);
Scribe_Values.Look(ref nextUpdateTick, "nextUpdateTick", 0);
Scribe_Values.Look(ref noTargetTicks, "noTargetTicks", 0);
Scribe_References.Look(ref currentTarget, "currentTarget");
Scribe_Values.Look(ref lastTargetPosition, "lastTargetPosition", IntVec3.Invalid);
Scribe_References.Look(ref activeLance, "activeLance");
}
}
public enum EnergyLanceState
{
Idle,
Searching,
Tracking,
NoTarget
}
}

View File

@@ -0,0 +1,28 @@
using RimWorld;
using Verse;
namespace WulaFallenEmpire
{
public class CompProperties_BuildingEnergyLance : CompProperties
{
// 基础配置
public float radius = 20f; // 作用半径
public int updateIntervalTicks = 30; // 目标更新间隔(刻)
public int maxNoTargetTicks = 120; // 无目标时最大存活时间
// 目标选择配置
public bool targetEnemies = true; // 是否以敌人为目标
public bool targetNeutrals = false; // 是否以中立单位为目标
public bool targetAnimals = false; // 是否以动物为目标
// EnergyLance配置
public ThingDef energyLanceDef; // 使用的EnergyLance类型
public int energyLanceDuration = 600; // EnergyLance基础持续时间
public int firesPerTick = 3; // 每刻伤害次数
public CompProperties_BuildingEnergyLance()
{
this.compClass = typeof(CompBuildingEnergyLance);
}
}
}

View File

@@ -0,0 +1,255 @@
using RimWorld;
using Verse;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
namespace WulaFallenEmpire
{
public class GuidedEnergyLance : OrbitalStrike
{
// 引导相关属性
public Thing controlBuilding; // 控制建筑
private IntVec3 currentTarget = IntVec3.Invalid; // 当前目标位置
private int lastTargetUpdateTick = -1; // 最后收到目标更新的刻
private int maxNoUpdateTicks = 60; // 无更新时的最大存活时间
// 移动配置
public float moveSpeed = 2.0f; // 移动速度(格/秒)
public float turnSpeed = 90f; // 转向速度(度/秒)
// 状态
private Vector3 currentVelocity;
private bool hasValidTarget = false;
// ModExtension引用
private EnergyLanceExtension extension;
private static List<Thing> tmpThings = new List<Thing>();
public override void StartStrike()
{
base.StartStrike();
// 获取ModExtension
extension = def.GetModExtension<EnergyLanceExtension>();
if (extension == null)
{
Log.Error($"[GuidedEnergyLance] No EnergyLanceExtension found on {def.defName}");
return;
}
lastTargetUpdateTick = Find.TickManager.TicksGame;
// 创建视觉效果
CreateVisualEffect();
Log.Message($"[GuidedEnergyLance] Guided EnergyLance started, controlled by {controlBuilding?.Label ?? "None"}");
}
private void CreateVisualEffect()
{
// 使用ModExtension中定义的Mote如果没有则使用默认的PowerBeam
if (extension.moteDef != null)
{
Mote mote = MoteMaker.MakeStaticMote(base.Position, base.Map, extension.moteDef);
}
else
{
// 使用原版PowerBeam的视觉效果
MoteMaker.MakePowerBeamMote(base.Position, base.Map);
}
}
protected override void Tick()
{
base.Tick();
if (!base.Destroyed && extension != null)
{
// 检查目标更新状态
CheckTargetStatus();
// 移动光束
MoveBeam();
// 造成伤害
for (int i = 0; i < firesPerTick; i++)
{
DoBeamDamage();
}
}
}
private void CheckTargetStatus()
{
int currentTick = Find.TickManager.TicksGame;
int ticksSinceUpdate = currentTick - lastTargetUpdateTick;
// 检查是否长时间未收到更新
if (ticksSinceUpdate >= maxNoUpdateTicks)
{
Log.Message($"[GuidedEnergyLance] No target updates for {ticksSinceUpdate} ticks, destroying");
Destroy();
return;
}
// 检查控制建筑状态
if (controlBuilding == null || controlBuilding.Destroyed || !controlBuilding.Spawned)
{
Log.Message($"[GuidedEnergyLance] Control building lost, destroying");
Destroy();
return;
}
}
private void MoveBeam()
{
if (!hasValidTarget || !currentTarget.IsValid)
{
// 没有有效目标,缓慢移动或保持原地
ApplyMinimalMovement();
return;
}
// 计算移动方向
Vector3 targetDirection = (currentTarget.ToVector3() - base.Position.ToVector3()).normalized;
// 平滑转向
if (currentVelocity.magnitude > 0.1f)
{
float maxTurnAngle = turnSpeed * 0.0167f; // 每帧最大转向角度假设60FPS
currentVelocity = Vector3.RotateTowards(currentVelocity, targetDirection, maxTurnAngle * Mathf.Deg2Rad, moveSpeed * 0.0167f);
}
else
{
currentVelocity = targetDirection * moveSpeed * 0.0167f;
}
// 应用移动
Vector3 newPos = base.Position.ToVector3() + currentVelocity;
IntVec3 newCell = new IntVec3(Mathf.RoundToInt(newPos.x), 0, Mathf.RoundToInt(newPos.z));
if (newCell != base.Position && newCell.InBounds(base.Map))
{
base.Position = newCell;
}
// 检查是否接近目标
float distanceToTarget = Vector3.Distance(base.Position.ToVector3(), currentTarget.ToVector3());
if (distanceToTarget < 1.5f)
{
// 到达目标附近,可以减速或保持位置
currentVelocity *= 0.8f;
}
Log.Message($"[GuidedEnergyLance] Moving to {currentTarget}, distance: {distanceToTarget:F1}");
}
private void ApplyMinimalMovement()
{
// 无目标时的最小移动,防止完全静止
if (currentVelocity.magnitude < 0.1f)
{
// 随机轻微移动
currentVelocity = new Vector3(Rand.Range(-0.1f, 0.1f), 0f, Rand.Range(-0.1f, 0.1f));
}
else
{
// 缓慢减速
currentVelocity *= 0.95f;
}
Vector3 newPos = base.Position.ToVector3() + currentVelocity;
IntVec3 newCell = new IntVec3(Mathf.RoundToInt(newPos.x), 0, Mathf.RoundToInt(newPos.z));
if (newCell != base.Position && newCell.InBounds(base.Map))
{
base.Position = newCell;
}
}
private void DoBeamDamage()
{
if (extension == null) return;
// 在当前光束位置周围随机选择一个单元格
IntVec3 targetCell = (from x in GenRadial.RadialCellsAround(base.Position, 2f, useCenter: true)
where x.InBounds(base.Map)
select x).RandomElementByWeight((IntVec3 x) => 1f - Mathf.Min(x.DistanceTo(base.Position) / 2f, 1f) + 0.05f);
// 尝试在该单元格点火(如果配置了点火)
if (extension.igniteFires)
{
FireUtility.TryStartFireIn(targetCell, base.Map, Rand.Range(0.1f, extension.fireIgniteChance), instigator);
}
// 对该单元格内的物体造成伤害
tmpThings.Clear();
tmpThings.AddRange(targetCell.GetThingList(base.Map));
for (int i = 0; i < tmpThings.Count; i++)
{
Thing thing = tmpThings[i];
// 检查是否对尸体造成伤害
if (!extension.applyDamageToCorpses && thing is Corpse)
continue;
// 计算伤害量
int damageAmount = (thing is Corpse) ?
extension.corpseDamageAmountRange.RandomInRange :
extension.damageAmountRange.RandomInRange;
Pawn pawn = thing as Pawn;
BattleLogEntry_DamageTaken battleLogEntry = null;
if (pawn != null)
{
battleLogEntry = new BattleLogEntry_DamageTaken(pawn, RulePackDefOf.DamageEvent_PowerBeam, instigator as Pawn);
Find.BattleLog.Add(battleLogEntry);
}
// 使用ModExtension中定义的伤害类型
DamageInfo damageInfo = new DamageInfo(extension.damageDef, damageAmount, 0f, -1f, instigator, null, weaponDef);
thing.TakeDamage(damageInfo).AssociateWithLog(battleLogEntry);
}
tmpThings.Clear();
}
// 外部调用:更新目标位置
public void UpdateTarget(IntVec3 newTarget)
{
lastTargetUpdateTick = Find.TickManager.TicksGame;
if (newTarget.IsValid && newTarget.InBounds(base.Map))
{
currentTarget = newTarget;
hasValidTarget = true;
Log.Message($"[GuidedEnergyLance] Target updated to {newTarget}");
}
else
{
hasValidTarget = false;
currentTarget = IntVec3.Invalid;
Log.Message($"[GuidedEnergyLance] Target cleared");
}
}
public override void ExposeData()
{
base.ExposeData();
Scribe_References.Look(ref controlBuilding, "controlBuilding");
Scribe_Values.Look(ref currentTarget, "currentTarget", IntVec3.Invalid);
Scribe_Values.Look(ref lastTargetUpdateTick, "lastTargetUpdateTick", -1);
Scribe_Values.Look(ref maxNoUpdateTicks, "maxNoUpdateTicks", 60);
Scribe_Values.Look(ref moveSpeed, "moveSpeed", 2.0f);
Scribe_Values.Look(ref turnSpeed, "turnSpeed", 90f);
Scribe_Values.Look(ref firesPerTick, "firesPerTick", 3);
}
}
}