添加 CombatNodeComponent 及相关类

- CombatNodeComponent:节点组件,负责提取并开始关卡
- CombatScheduler:关卡调度器,负责关卡的生命周期调度
- MapEntity:地图实体,提供地图相关的数据
- Spawner:出生点,负责标记地图上的敌人出生点坐标
- House:基地,负责标记地图上的敌人目标点坐标
This commit is contained in:
SepComet
2026-02-28 15:44:22 +08:00
parent d9c118ace3
commit dd9cedef5f
91 changed files with 37977 additions and 651 deletions
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using GeometryTD.Definition;
using UnityEngine;
@@ -14,6 +15,8 @@ namespace GeometryTD.Entity.EntityData
[SerializeField] private float _speed = 0;
[SerializeField] private Transform _player = null;
[SerializeField] private List<Vector3> _pathPoints = new List<Vector3>();
public EnemyData(int entityId, int typeId, Transform player, Vector3 pos, int maxHp, float speed) : base(
entityId, typeId)
@@ -22,6 +25,17 @@ namespace GeometryTD.Entity.EntityData
_speed = speed;
Position = pos;
_player = player;
_pathPoints.Clear();
}
public EnemyData(int entityId, int typeId, Vector3 pos, int maxHp, float speed,
IReadOnlyList<Vector3> pathPoints) : base(entityId, typeId)
{
_maxHealth = maxHp;
_speed = speed;
Position = pos;
_player = null;
SetPathPoints(pathPoints);
}
public CampType Camp
@@ -47,5 +61,23 @@ namespace GeometryTD.Entity.EntityData
get => _player;
set => _player = value;
}
public IReadOnlyList<Vector3> PathPoints => _pathPoints;
public bool HasPath => _pathPoints.Count > 0;
public void SetPathPoints(IReadOnlyList<Vector3> pathPoints)
{
_pathPoints.Clear();
if (pathPoints == null)
{
return;
}
for (int i = 0; i < pathPoints.Count; i++)
{
_pathPoints.Add(pathPoints[i]);
}
}
}
}
}
@@ -13,41 +13,37 @@ namespace GeometryTD.Entity.EntityData
[Serializable]
public abstract class EntityDataBase
{
[SerializeField]
private int m_Id = 0;
[SerializeField] private int _id = 0;
[SerializeField]
private int m_TypeId = 0;
[SerializeField] private int _typeId = 0;
[SerializeField]
private Vector3 m_Position = Vector3.zero;
[SerializeField] private Vector3 _position = Vector3.zero;
[SerializeField]
private Quaternion m_Rotation = Quaternion.identity;
[SerializeField] private Quaternion _rotation = Quaternion.identity;
public EntityDataBase(int entityId, int typeId)
{
m_Id = entityId;
m_TypeId = typeId;
_id = entityId;
_typeId = typeId;
}
/// <summary>
/// 实体编号。
/// 生成的实体编号。
/// </summary>
public int Id => m_Id;
public int Id => _id;
/// <summary>
/// 实体类型编号。
/// 实体类型编号(外键)。
/// </summary>
public int TypeId => m_TypeId;
public int TypeId => _typeId;
/// <summary>
/// 实体位置。
/// </summary>
public Vector3 Position
{
get => m_Position;
set => m_Position = value;
get => _position;
set => _position = value;
}
/// <summary>
@@ -55,8 +51,8 @@ namespace GeometryTD.Entity.EntityData
/// </summary>
public Quaternion Rotation
{
get => m_Rotation;
set => m_Rotation = value;
get => _rotation;
set => _rotation = value;
}
}
}
}
@@ -0,0 +1,27 @@
using System;
using UnityEngine;
namespace GeometryTD.Entity.EntityData
{
[Serializable]
public class MapData : EntityDataBase
{
[SerializeField] private int _levelId = 0;
public MapData(int entityId, int levelId, Vector3 position) : this(entityId, 0, levelId, position)
{
}
public MapData(int entityId, int typeId, int levelId, Vector3 position) : base(entityId, typeId)
{
_levelId = levelId;
Position = position;
}
public int LevelId
{
get => _levelId;
set => _levelId = value;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c2635b0451d8c944ea0a5761ebc53d51
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -48,7 +48,25 @@ namespace GeometryTD
public static void ShowEnemy(this EntityComponent entityComponent, EnemyData data)
{
entityComponent.ShowEntity(typeof(Enemy), "Enemy", Constant.AssetPriority.EnemyAsset, data);
entityComponent.ShowEntity(typeof(EnemyEntity), "Enemy", Constant.AssetPriority.EnemyAsset, data);
}
public static void ShowMap(this EntityComponent entityComponent, MapData data)
{
ShowMap(entityComponent, data, null);
}
public static void ShowMap(this EntityComponent entityComponent, MapData data, string mapAssetName)
{
if (data == null)
{
Log.Warning("Map data is invalid.");
return;
}
string resolvedMapAssetName = string.IsNullOrEmpty(mapAssetName) ? data.LevelId.ToString() : mapAssetName;
string mapAssetPath = AssetUtility.GetLevelMapAsset(resolvedMapAssetName);
entityComponent.ShowEntity(data.Id, typeof(MapEntity), mapAssetPath, "Map", Constant.AssetPriority.MapAsset, data);
}
private static void ShowEntity(this EntityComponent entityComponent, Type logicType, string entityGroup,
@@ -77,4 +95,4 @@ namespace GeometryTD
return --s_SerialId;
}
}
}
}
@@ -1,69 +0,0 @@
using Components;
using GeometryTD.Entity.EntityData;
using UnityEngine;
namespace GeometryTD.Entity
{
public class Enemy : EntityBase
{
private Transform _target;
private float _speed;
private MovementComponent _movementComponent;
private float _attackRange = 1f;
private float _attackRangeSquared;
protected override void OnInit(object userData)
{
base.OnInit(userData);
_movementComponent = GetComponent<MovementComponent>();
}
protected override void OnShow(object userData)
{
base.OnShow(userData);
if (userData is EnemyData enemyData)
{
_speed = enemyData.Speed;
_target = enemyData.Player;
}
_movementComponent.OnInit(_speed, this.CachedTransform);
_movementComponent.SetMove(true);
_attackRangeSquared = _attackRange * _attackRange;
}
protected override void OnUpdate(float elapseSeconds, float realElapseSeconds)
{
base.OnUpdate(elapseSeconds, realElapseSeconds);
float distanceSquared = (this.CachedTransform.position - _target.position).sqrMagnitude;
if (distanceSquared < _attackRangeSquared)
{
// 攻击
_movementComponent.SetMove(false);
}
else
{
_movementComponent.SetMove(true);
_movementComponent.SetDirection(GetTargetDirection());
}
_movementComponent.OnUpdate(elapseSeconds, realElapseSeconds);
}
protected override void OnHide(bool isShutdown, object userData)
{
_movementComponent.SetMove(false);
base.OnHide(isShutdown, userData);
}
private Vector3 GetTargetDirection()
{
return new Vector3(_target.position.x - this.CachedTransform.position.x, 0f,
_target.position.z - this.CachedTransform.position.z).normalized;
}
}
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 112f2a17ab82438484782c9a763fdee1
timeCreated: 1768892870
@@ -0,0 +1,134 @@
using Components;
using System.Collections.Generic;
using GeometryTD.Entity.EntityData;
using UnityEngine;
namespace GeometryTD.Entity
{
public class EnemyEntity : EntityBase
{
private const float WaypointReachDistance = 0.05f;
private Transform _target;
private float _speed;
private MovementComponent _movementComponent;
private readonly List<Vector3> _pathPoints = new List<Vector3>();
private int _pathPointIndex;
private bool _isDespawnRequested;
protected override void OnInit(object userData)
{
base.OnInit(userData);
_movementComponent = GetComponent<MovementComponent>();
}
protected override void OnShow(object userData)
{
base.OnShow(userData);
_target = null;
_pathPoints.Clear();
_pathPointIndex = 0;
_isDespawnRequested = false;
if (userData is EnemyData enemyData)
{
_speed = enemyData.Speed;
_target = enemyData.Player;
if (enemyData.HasPath)
{
IReadOnlyList<Vector3> pathPoints = enemyData.PathPoints;
for (int i = 0; i < pathPoints.Count; i++)
{
_pathPoints.Add(pathPoints[i]);
}
}
}
_movementComponent.OnInit(_speed, CachedTransform);
_movementComponent.SetMove(true);
}
protected override void OnUpdate(float elapseSeconds, float realElapseSeconds)
{
base.OnUpdate(elapseSeconds, realElapseSeconds);
if (_pathPoints.Count > 0)
{
UpdatePathMovement(elapseSeconds, realElapseSeconds);
return;
}
}
protected override void OnHide(bool isShutdown, object userData)
{
_movementComponent.SetMove(false);
_pathPoints.Clear();
_pathPointIndex = 0;
_isDespawnRequested = false;
base.OnHide(isShutdown, userData);
}
private void UpdatePathMovement(float elapseSeconds, float realElapseSeconds)
{
if (_isDespawnRequested)
{
return;
}
if (_pathPointIndex >= _pathPoints.Count)
{
DespawnOnReachHouse();
return;
}
Vector3 direction = GetDirectionToPathPoint(_pathPoints[_pathPointIndex], out float distanceSquared);
if (distanceSquared <= WaypointReachDistance * WaypointReachDistance)
{
_pathPointIndex++;
if (_pathPointIndex >= _pathPoints.Count)
{
DespawnOnReachHouse();
return;
}
direction = GetDirectionToPathPoint(_pathPoints[_pathPointIndex], out _);
}
if (direction.sqrMagnitude <= Mathf.Epsilon)
{
_movementComponent.SetMove(false);
return;
}
_movementComponent.SetMove(true);
_movementComponent.SetDirection(direction);
_movementComponent.OnUpdate(elapseSeconds, realElapseSeconds);
}
private Vector3 GetDirectionToPathPoint(Vector3 worldPoint, out float distanceSquared)
{
Vector3 delta = worldPoint - CachedTransform.position;
distanceSquared = delta.sqrMagnitude;
if (distanceSquared <= Mathf.Epsilon)
{
return Vector3.zero;
}
return delta.normalized;
}
private void DespawnOnReachHouse()
{
if (_isDespawnRequested)
{
return;
}
_isDespawnRequested = true;
_movementComponent.SetMove(false);
GameEntry.Entity.HideEntity(Entity);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ec17059949d1140428bd47809397a01f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,300 @@
using System;
using System.Collections.Generic;
using GeometryTD.Entity.EntityData;
using GeometryTD.Pathfinding;
using UnityEngine;
using UnityEngine.Tilemaps;
using UnityGameFramework.Runtime;
namespace GeometryTD.Entity
{
public class MapEntity : EntityBase
{
private const string PathTileName = "Path";
private const string FoundationTileName = "Foundation";
private static readonly Spawner[] EmptySpawners = Array.Empty<Spawner>();
private readonly List<Vector3Int> _pathCells = new();
private readonly List<Vector3Int> _foundationCells = new();
private readonly HashSet<Vector3Int> _pathCellSet = new();
private readonly HashSet<Vector3Int> _foundationCellSet = new();
private readonly IMapPathfinder _mapPathfinder = new GridMapPathfinder();
private readonly List<Vector3Int> _pathCellBuffer = new();
private readonly Dictionary<Spawner, Vector3Int> _spawnerPathStartByRef = new();
private readonly Dictionary<Spawner, List<Vector3Int>> _defaultPathCellsBySpawner = new();
private MapDataRefs _mapDataRefs;
private MapData _mapData;
private bool _hasHousePathCell;
private Vector3Int _housePathCell;
public IReadOnlyList<Vector3Int> PathCells => _pathCells;
public IReadOnlyList<Vector3Int> FoundationCells => _foundationCells;
public Tilemap Tilemap => _mapDataRefs != null ? _mapDataRefs.Tilemap : null;
public Spawner[] Spawners => _mapDataRefs?.Spawners ?? EmptySpawners;
public House House => _mapDataRefs?.House;
public bool IsPathCell(Vector3Int cellPosition)
{
return _pathCellSet.Contains(cellPosition);
}
public bool IsFoundationCell(Vector3Int cellPosition)
{
return _foundationCellSet.Contains(cellPosition);
}
public bool TryGetNearestPathCell(Vector3 worldPosition, out Vector3Int pathCell)
{
pathCell = default;
if (_pathCells.Count <= 0 || Tilemap == null)
{
return false;
}
Vector3Int directCell = Tilemap.WorldToCell(worldPosition);
if (_pathCellSet.Contains(directCell))
{
pathCell = directCell;
return true;
}
float minDistance = float.MaxValue;
for (int i = 0; i < _pathCells.Count; i++)
{
Vector3Int candidate = _pathCells[i];
float distance = (Tilemap.GetCellCenterWorld(candidate) - worldPosition).sqrMagnitude;
if (distance >= minDistance)
{
continue;
}
minDistance = distance;
pathCell = candidate;
}
return minDistance < float.MaxValue;
}
public Vector3 GetPathCellCenterWorld(Vector3Int pathCell)
{
return Tilemap != null ? Tilemap.GetCellCenterWorld(pathCell) : Vector3.zero;
}
public bool TryGetDefaultPathCells(Spawner spawner, out IReadOnlyList<Vector3Int> pathCells)
{
pathCells = null;
if (spawner == null)
{
return false;
}
if (!_defaultPathCellsBySpawner.TryGetValue(spawner, out List<Vector3Int> cachedPathCells))
{
return false;
}
pathCells = cachedPathCells;
return true;
}
public bool TryFindPathCells(Spawner spawner, IReadOnlyCollection<Vector3Int> blockedCells,
List<Vector3Int> pathResult)
{
if (pathResult == null)
{
return false;
}
pathResult.Clear();
if (spawner == null || !_hasHousePathCell)
{
return false;
}
if (!_spawnerPathStartByRef.TryGetValue(spawner, out Vector3Int startCell))
{
return false;
}
return _mapPathfinder.TryFindPath(_pathCells, startCell, _housePathCell, blockedCells, pathResult);
}
public bool TryFindPathWorldPoints(Spawner spawner, IReadOnlyCollection<Vector3Int> blockedCells,
List<Vector3> worldPathResult)
{
if (worldPathResult == null)
{
return false;
}
worldPathResult.Clear();
if (Tilemap == null)
{
return false;
}
if (!TryFindPathCells(spawner, blockedCells, _pathCellBuffer))
{
return false;
}
foreach (var pos in _pathCellBuffer)
{
worldPathResult.Add(GetPathCellCenterWorld(pos));
}
return true;
}
protected override void OnInit(object userData)
{
base.OnInit(userData);
_mapDataRefs = GetComponent<MapDataRefs>();
if (_mapDataRefs == null)
{
Log.Error("MapDataRefs is missing on map entity '{0}'.", name);
}
}
protected override void OnShow(object userData)
{
base.OnShow(userData);
_mapData = userData as MapData;
if (_mapData == null)
{
Log.Warning("MapData is invalid for map entity '{0}'.", Id);
}
RefreshTiles();
}
protected override void OnHide(bool isShutdown, object userData)
{
ClearRuntimeData();
base.OnHide(isShutdown, userData);
}
private void RefreshTiles()
{
ClearRuntimeData();
if (_mapDataRefs == null)
{
_mapDataRefs = GetComponent<MapDataRefs>();
if (_mapDataRefs == null)
{
Log.Error("MapDataRefs is missing on map entity '{0}'.", name);
return;
}
}
Tilemap tilemap = _mapDataRefs.Tilemap;
if (tilemap == null)
{
Log.Error("Tilemap reference is missing in MapDataRefs on '{0}'.", name);
return;
}
BoundsInt bounds = tilemap.cellBounds;
foreach (Vector3Int cellPosition in bounds.allPositionsWithin)
{
TileBase tile = tilemap.GetTile(cellPosition);
if (tile == null || string.IsNullOrEmpty(tile.name))
{
continue;
}
if (string.Equals(tile.name, PathTileName, StringComparison.Ordinal))
{
_pathCells.Add(cellPosition);
_pathCellSet.Add(cellPosition);
continue;
}
if (string.Equals(tile.name, FoundationTileName, StringComparison.Ordinal))
{
_foundationCells.Add(cellPosition);
_foundationCellSet.Add(cellPosition);
}
}
RefreshPathCache();
Log.Info(
"Map '{0}' initialized. LevelId={1}, PathCells={2}, FoundationCells={3}, Spawners={4}, House={5}, Routes={6}.",
name,
_mapData != null ? _mapData.LevelId : 0,
_pathCells.Count,
_foundationCells.Count,
Spawners.Length,
House != null ? House.name : "None",
_defaultPathCellsBySpawner.Count);
}
private void RefreshPathCache()
{
_hasHousePathCell = false;
_housePathCell = default;
_spawnerPathStartByRef.Clear();
_defaultPathCellsBySpawner.Clear();
if (House == null)
{
Log.Warning("Map '{0}' has no house reference, path cache skipped.", name);
return;
}
if (!TryGetNearestPathCell(House.Position, out _housePathCell))
{
Log.Warning("Map '{0}' house position can not map to a valid path cell.", name);
return;
}
_hasHousePathCell = true;
Spawner[] spawners = Spawners;
foreach (var spawner in spawners)
{
if (spawner == null)
{
continue;
}
if (!TryGetNearestPathCell(spawner.Position, out Vector3Int startCell))
{
Log.Warning("Map '{0}' spawner '{1}' can not map to a valid path cell.", name, spawner.name);
continue;
}
_spawnerPathStartByRef[spawner] = startCell;
List<Vector3Int> defaultPathCells = new List<Vector3Int>();
if (!_mapPathfinder.TryFindPath(_pathCells, startCell, _housePathCell, null, defaultPathCells))
{
Log.Warning(
"Map '{0}' spawner '{1}' has no path to house cell {2}.",
name,
spawner.name,
_housePathCell);
continue;
}
_defaultPathCellsBySpawner[spawner] = defaultPathCells;
}
}
private void ClearRuntimeData()
{
_pathCells.Clear();
_foundationCells.Clear();
_pathCellSet.Clear();
_foundationCellSet.Clear();
_pathCellBuffer.Clear();
_hasHousePathCell = false;
_housePathCell = default;
_spawnerPathStartByRef.Clear();
_defaultPathCellsBySpawner.Clear();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9d45242aa35912c46a0260f67e3b2ae0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: