ThreatSourceLibaray/docs/examples/Integration/UnityExample.cs

427 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#if NEVER // 使用编译指令确保此文件永远不会被编译
// Unity引擎集成示例代码
// 展示如何将Unity引擎与ThreatSource仿真系统集成
// 需要实现的核心功能: 实体同步、事件处理、状态管理
using ThreatSource.Simulation;
using ThreatSource.Data;
using ThreatSource.Missile;
using UnityEngine; // 仅用于示例实际项目中需要引用真实的Unity命名空间
/// <summary>
/// Unity引擎适配器类演示如何将Unity引擎集成到仿真系统中
/// </summary>
/// <remarks>
/// 该类提供了以下功能:
/// - Unity引擎与仿真系统的双向通信
/// - GameObject与仿真实体的映射和同步
/// - MonoBehaviour生命周期管理
/// - 事件的发布和订阅
/// 本示例代码仅作为参考,展示了基本的集成方法
/// </remarks>
public class UnityThreatSourceAdapter : MonoBehaviour
{
/// <summary>
/// 仿真管理器实例
/// </summary>
private ISimulationManager _simulationManager;
/// <summary>
/// 数据管理器实例
/// </summary>
private ThreatSourceDataManager _dataManager;
/// <summary>
/// 实体映射字典仿真实体ID -> Unity GameObject
/// </summary>
private Dictionary<string, GameObject> _entityGameObjects = new Dictionary<string, GameObject>();
/// <summary>
/// 导弹预制体路径
/// </summary>
[SerializeField]
private string missilePrefabPath = "Prefabs/Missile";
/// <summary>
/// 目标预制体路径
/// </summary>
[SerializeField]
private string targetPrefabPath = "Prefabs/Target";
/// <summary>
/// 仿真时间步长
/// </summary>
[SerializeField]
private float simulationTimeStep = 0.02f;
/// <summary>
/// Unity生命周期方法初始化
/// </summary>
private void Awake()
{
InitializeSimulation();
}
/// <summary>
/// 初始化仿真系统
/// </summary>
private void InitializeSimulation()
{
try
{
// 创建仿真管理器和数据管理器
_simulationManager = new SimulationManager();
_dataManager = new ThreatSourceDataManager();
// 启动仿真
_simulationManager.StartSimulation(simulationTimeStep);
// 订阅仿真事件
_simulationManager.Subscribe<MissileFireEvent>(OnMissileFireEvent);
_simulationManager.Subscribe<MissileExplodeEvent>(OnMissileExplodeEvent);
_simulationManager.Subscribe<FlightPhaseChangeEvent>(OnFlightPhaseChangeEvent);
Debug.Log("ThreatSource仿真系统初始化成功");
}
catch (System.Exception ex)
{
Debug.LogError($"仿真系统初始化失败: {ex.Message}");
}
}
/// <summary>
/// Unity生命周期方法更新
/// </summary>
private void Update()
{
if (_simulationManager != null)
{
// 更新仿真
_simulationManager.UpdateSimulation();
// 同步实体状态
SyncEntityStates();
}
}
/// <summary>
/// 同步仿真实体状态到Unity GameObject
/// </summary>
private void SyncEntityStates()
{
foreach (var kvp in _entityGameObjects)
{
string entityId = kvp.Key;
GameObject gameObject = kvp.Value;
// 获取仿真实体
var entity = _simulationManager.GetEntity(entityId);
if (entity != null && entity.KState != null)
{
// 同步位置
gameObject.transform.position = new Vector3(
entity.KState.Position.X,
entity.KState.Position.Z, // Unity使用Y作为高度
entity.KState.Position.Y
);
// 同步旋转
var orientation = entity.KState.Orientation;
gameObject.transform.rotation = Quaternion.Euler(
orientation.Pitch * Mathf.Rad2Deg,
orientation.Yaw * Mathf.Rad2Deg,
orientation.Roll * Mathf.Rad2Deg
);
}
}
}
/// <summary>
/// 创建导弹实体
/// </summary>
/// <param name="missileType">导弹类型</param>
/// <param name="position">初始位置</param>
/// <param name="targetId">目标ID</param>
public void CreateMissile(string missileType, Vector3 position, string targetId)
{
try
{
// 从配置创建导弹
var missileData = _dataManager.GetMissile(missileType);
string missileId = $"missile_{System.Guid.NewGuid():N}";
var missile = new InfraredImagingTerminalGuidanceMissile(missileId, missileData)
{
KState = new KinematicState
{
Position = new ThreatSource.Simulation.Vector3(position.x, position.z, position.y),
Velocity = new ThreatSource.Simulation.Vector3(0, 0, 0),
Orientation = new Orientation(0, 0, 0)
}
};
// 注册到仿真系统
_simulationManager.RegisterEntity(missile);
// 在Unity中创建GameObject
var missilePrefab = Resources.Load<GameObject>(missilePrefabPath);
if (missilePrefab != null)
{
var missileGameObject = Instantiate(missilePrefab, position, Quaternion.identity);
missileGameObject.name = missileId;
// 添加导弹控制组件
var missileController = missileGameObject.GetComponent<MissileController>();
if (missileController == null)
{
missileController = missileGameObject.AddComponent<MissileController>();
}
missileController.Initialize(missileId, targetId);
// 建立映射关系
_entityGameObjects[missileId] = missileGameObject;
Debug.Log($"创建导弹: {missileId}, 目标: {targetId}");
}
else
{
Debug.LogError($"无法加载导弹预制体: {missilePrefabPath}");
}
}
catch (System.Exception ex)
{
Debug.LogError($"创建导弹失败: {ex.Message}");
}
}
/// <summary>
/// 创建目标实体
/// </summary>
/// <param name="targetId">目标ID</param>
/// <param name="position">位置</param>
/// <param name="velocity">速度</param>
public void CreateTarget(string targetId, Vector3 position, Vector3 velocity)
{
try
{
// 创建目标实体
var target = new BaseEquipment(targetId)
{
KState = new KinematicState
{
Position = new ThreatSource.Simulation.Vector3(position.x, position.z, position.y),
Velocity = new ThreatSource.Simulation.Vector3(velocity.x, velocity.z, velocity.y),
Orientation = new Orientation(0, 0, 0)
}
};
// 注册到仿真系统
_simulationManager.RegisterEntity(target);
// 在Unity中创建GameObject
var targetPrefab = Resources.Load<GameObject>(targetPrefabPath);
if (targetPrefab != null)
{
var targetGameObject = Instantiate(targetPrefab, position, Quaternion.identity);
targetGameObject.name = targetId;
// 建立映射关系
_entityGameObjects[targetId] = targetGameObject;
Debug.Log($"创建目标: {targetId}");
}
else
{
Debug.LogError($"无法加载目标预制体: {targetPrefabPath}");
}
}
catch (System.Exception ex)
{
Debug.LogError($"创建目标失败: {ex.Message}");
}
}
/// <summary>
/// 处理导弹发射事件
/// </summary>
private void OnMissileFireEvent(MissileFireEvent evt)
{
Debug.Log($"导弹发射事件: {evt.SenderId} -> {evt.TargetId}");
// 可以在这里添加视觉效果,如发射烟雾、声音等
var missileGameObject = GetGameObject(evt.SenderId);
if (missileGameObject != null)
{
// 播放发射特效
var particleSystem = missileGameObject.GetComponentInChildren<ParticleSystem>();
if (particleSystem != null)
{
particleSystem.Play();
}
}
}
/// <summary>
/// 处理导弹爆炸事件
/// </summary>
private void OnMissileExplodeEvent(MissileExplodeEvent evt)
{
Debug.Log($"导弹爆炸事件: {evt.SenderId} 在位置 {evt.Position}");
var missileGameObject = GetGameObject(evt.SenderId);
if (missileGameObject != null)
{
// 播放爆炸特效
var explosionPrefab = Resources.Load<GameObject>("Prefabs/Explosion");
if (explosionPrefab != null)
{
Instantiate(explosionPrefab, missileGameObject.transform.position, Quaternion.identity);
}
// 销毁导弹GameObject
Destroy(missileGameObject);
_entityGameObjects.Remove(evt.SenderId);
}
}
/// <summary>
/// 处理飞行阶段变化事件
/// </summary>
private void OnFlightPhaseChangeEvent(FlightPhaseChangeEvent evt)
{
Debug.Log($"导弹 {evt.SenderId} 进入 {evt.NewPhase} 阶段");
// 可以根据飞行阶段改变导弹的视觉表现
var missileGameObject = GetGameObject(evt.SenderId);
if (missileGameObject != null)
{
var missileController = missileGameObject.GetComponent<MissileController>();
if (missileController != null)
{
missileController.OnFlightPhaseChanged(evt.NewPhase);
}
}
}
/// <summary>
/// 根据实体ID获取对应的GameObject
/// </summary>
private GameObject GetGameObject(string entityId)
{
_entityGameObjects.TryGetValue(entityId, out GameObject gameObject);
return gameObject;
}
/// <summary>
/// Unity生命周期方法销毁
/// </summary>
private void OnDestroy()
{
CleanupSimulation();
}
/// <summary>
/// 清理仿真系统
/// </summary>
private void CleanupSimulation()
{
if (_simulationManager != null)
{
_simulationManager.StopSimulation();
_simulationManager = null;
}
// 清理GameObject映射
foreach (var gameObject in _entityGameObjects.Values)
{
if (gameObject != null)
{
Destroy(gameObject);
}
}
_entityGameObjects.Clear();
Debug.Log("ThreatSource仿真系统已清理");
}
}
/// <summary>
/// 导弹控制器组件
/// </summary>
public class MissileController : MonoBehaviour
{
private string _missileId;
private string _targetId;
private TrailRenderer _trailRenderer;
public void Initialize(string missileId, string targetId)
{
_missileId = missileId;
_targetId = targetId;
// 获取拖尾渲染器
_trailRenderer = GetComponent<TrailRenderer>();
if (_trailRenderer == null)
{
_trailRenderer = gameObject.AddComponent<TrailRenderer>();
}
}
public void OnFlightPhaseChanged(FlightPhase newPhase)
{
// 根据飞行阶段调整视觉效果
switch (newPhase)
{
case FlightPhase.Boost:
// 助推阶段:显示推进器火焰
break;
case FlightPhase.Midcourse:
// 中段飞行:调整拖尾效果
if (_trailRenderer != null)
{
_trailRenderer.enabled = true;
}
break;
case FlightPhase.Terminal:
// 末段制导:可能改变颜色或效果
if (_trailRenderer != null)
{
_trailRenderer.material.color = Color.red;
}
break;
}
}
}
/// <summary>
/// 示例使用脚本
/// </summary>
public class ThreatSourceExample : MonoBehaviour
{
private UnityThreatSourceAdapter _adapter;
private void Start()
{
// 获取适配器组件
_adapter = FindObjectOfType<UnityThreatSourceAdapter>();
if (_adapter == null)
{
_adapter = gameObject.AddComponent<UnityThreatSourceAdapter>();
}
// 延迟创建示例场景
Invoke(nameof(CreateExampleScene), 1.0f);
}
private void CreateExampleScene()
{
// 创建目标
_adapter.CreateTarget("target_001", new Vector3(1000, 0, 100), new Vector3(-50, 0, 0));
// 创建导弹
_adapter.CreateMissile("IR_Missile_Example", Vector3.zero, "target_001");
}
}
#endif // 结束编译指令块