替换玩家模型素材,添加 ChildrenMap 配置挂点

This commit is contained in:
2026-10-04 17:57:16 +08:00
parent 75ec52f3d4
commit aaa8cf3ee2
98 changed files with 6483 additions and 274 deletions
@@ -0,0 +1,31 @@
using GameFramework;
using GameFramework.Event;
namespace SepCore.Event
{
public class ItemTooltipCombineEventArgs : GameEventArgs
{
public static readonly int EventId = typeof(ItemTooltipCombineEventArgs).GetHashCode();
public override int Id => EventId;
public int Index;
public ItemTooltipCombineEventArgs()
{
Index = -1;
}
public static ItemTooltipCombineEventArgs Create(int index)
{
var args = ReferencePool.Acquire<ItemTooltipCombineEventArgs>();
args.Index = index;
return args;
}
public override void Clear()
{
Index = -1;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 06cccd1f29419fe4c866ffda3aea61af
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -50,7 +50,7 @@ public sealed partial class GlobalConfig : Luban.BeanBase
DamageTextYOffset = _buf.ReadInt();
EntityAsyncTimeout = _buf.ReadInt();
CritMultiplier = _buf.ReadFloat();
EnemyBodyRadius = _buf.ReadInt();
EnemyBodyRadius = _buf.ReadFloat();
EnemySeparationIterations = _buf.ReadInt();
}
@@ -192,7 +192,7 @@ public sealed partial class GlobalConfig : Luban.BeanBase
/// <summary>
/// 敌人碰撞半径
/// </summary>
public readonly int EnemyBodyRadius;
public readonly float EnemyBodyRadius;
/// <summary>
/// 敌人分离迭代次数
/// </summary>
@@ -17,6 +17,7 @@ public sealed partial class LevelExperienceConfig : Luban.BeanBase
public LevelExperienceConfig(ByteBuf _buf)
{
Key = _buf.ReadString();
Key_Ref = null;
Lv0 = _buf.ReadInt();
Lv1 = _buf.ReadInt();
Lv2 = _buf.ReadInt();
@@ -89,6 +90,7 @@ public sealed partial class LevelExperienceConfig : Luban.BeanBase
/// 角色名
/// </summary>
public readonly string Key;
public RoleConfig Key_Ref;
public readonly int Lv0;
public readonly int Lv1;
public readonly int Lv2;
@@ -156,7 +158,7 @@ public sealed partial class LevelExperienceConfig : Luban.BeanBase
public void ResolveRef(Tables tables)
{
Key_Ref = tables.TbRoleConfig.GetOrDefault(Key);
@@ -22,8 +22,8 @@ public sealed partial class RoleConfig : Luban.BeanBase
Coin = _buf.ReadInt();
{int n0 = System.Math.Min(_buf.ReadSize(), _buf.Size);StatModifierConfigs = new System.Collections.Generic.List<StatModifierConfig>(n0);for(var i0 = 0 ; i0 < n0 ; i0++) { StatModifierConfig _e0; _e0 = StatModifierConfig.DeserializeStatModifierConfig(_buf); StatModifierConfigs.Add(_e0);}}
{int n0 = System.Math.Min(_buf.ReadSize(), _buf.Size);InitialItems = new System.Collections.Generic.List<int>(n0);for(var i0 = 0 ; i0 < n0 ; i0++) { int _e0; _e0 = _buf.ReadInt(); InitialItems.Add(_e0);}}
Prefab = _buf.ReadString();
Prefab_Ref = null;
Texture = _buf.ReadString();
Texture_Ref = null;
Sprite = _buf.ReadString();
Sprite_Ref = null;
}
@@ -42,8 +42,8 @@ public sealed partial class RoleConfig : Luban.BeanBase
/// </summary>
public readonly System.Collections.Generic.List<StatModifierConfig> StatModifierConfigs;
public readonly System.Collections.Generic.List<int> InitialItems;
public readonly string Prefab;
public EntityConfig Prefab_Ref;
public readonly string Texture;
public SpriteConfig Texture_Ref;
public readonly string Sprite;
public SpriteConfig Sprite_Ref;
@@ -58,7 +58,7 @@ public sealed partial class RoleConfig : Luban.BeanBase
foreach (var _e in StatModifierConfigs) { _e?.ResolveRef(tables); }
Prefab_Ref = tables.TbEntityConfig.GetOrDefault(Prefab);
Texture_Ref = tables.TbSpriteConfig.GetOrDefault(Texture);
Sprite_Ref = tables.TbSpriteConfig.GetOrDefault(Sprite);
}
@@ -71,7 +71,7 @@ public sealed partial class RoleConfig : Luban.BeanBase
+ "coin:" + Coin + ","
+ "statModifierConfigs:" + Luban.StringUtil.CollectionToString(StatModifierConfigs) + ","
+ "initialItems:" + Luban.StringUtil.CollectionToString(InitialItems) + ","
+ "prefab:" + Prefab + ","
+ "texture:" + Texture + ","
+ "sprite:" + Sprite + ","
+ "}";
}
@@ -161,7 +161,7 @@ public partial class TbGlobalConfig
/// <summary>
/// 敌人碰撞半径
/// </summary>
public int EnemyBodyRadius => _data.EnemyBodyRadius;
public float EnemyBodyRadius => _data.EnemyBodyRadius;
/// <summary>
/// 敌人分离迭代次数
/// </summary>
@@ -27,6 +27,7 @@ namespace SepCore.UI
View.infoText.text = _context.Description;
View.textFormatText.Set(_context.Price);
View.recycleButton.gameObject.SetActive(_context.ShowRecycleButton);
View.combineButton.gameObject.SetActive(_context.ShowCombineButton);
View.iconArea.SetRarity(_context.Rarity);
ResizeToFitContent();
@@ -54,6 +55,14 @@ namespace SepCore.UI
}
}
public void OnCombineButtonClick()
{
if (_context != null)
{
GameEntry.Event.Fire(this, ItemTooltipCombineEventArgs.Create(_context.Index));
}
}
public void OnCancelButtonClick()
{
GameEntry.Event.Fire(this, ItemTooltipHideEventArgs.Create());
@@ -68,6 +77,7 @@ namespace SepCore.UI
_listenersBound = true;
View.recycleButton.onClick.AddListener(OnRecycleButtonClick);
View.combineButton.onClick.AddListener(OnCombineButtonClick);
View.cancelButton.onClick.AddListener(OnCancelButtonClick);
}
@@ -83,7 +93,12 @@ namespace SepCore.UI
descriptionSize.y = View.infoText.preferredHeight;
View.infoText.rectTransform.sizeDelta = descriptionSize;
float descriptionHeight = Mathf.Max(0f, View.infoText.preferredHeight);
float targetHeight = _fixedTopHeight + descriptionHeight + _fixedBottomHeight;
float bottomHeight = _fixedBottomHeight;
if (_context != null && _context.ShowCombineButton)
{
bottomHeight += 100f;
}
float targetHeight = _fixedTopHeight + descriptionHeight + bottomHeight;
Vector2 size = new Vector2(_fixedWidth, targetHeight);
View.contentRectTransform.sizeDelta = size;
@@ -12,6 +12,7 @@ namespace SepCore.UI
[SerializeField] public global::TMPro.TextMeshProUGUI typeText;
[SerializeField] public global::TMPro.TextMeshProUGUI infoText;
[SerializeField] public global::SepCore.UI.CommonButton recycleButton;
[SerializeField] public global::SepCore.UI.CommonButton combineButton;
[SerializeField] public global::SepCore.UI.FormatTextUI textFormatText;
[SerializeField] public global::SepCore.UI.CommonButton cancelButton;
}
@@ -15,6 +15,7 @@ namespace SepCore.UI
public string Description;
public int Price;
public bool ShowRecycleButton;
public bool ShowCombineButton;
public ItemBasicTooltipContext()
{
@@ -27,6 +28,7 @@ namespace SepCore.UI
Description = string.Empty;
Price = 0;
ShowRecycleButton = false;
ShowCombineButton = false;
}
public ItemBasicTooltipContext(ItemTooltipRawData rawData) : this()
@@ -41,6 +43,7 @@ namespace SepCore.UI
Rarity = rawData.Rarity;
Price = rawData.Price;
ShowRecycleButton = rawData.OnRecycle != null;
ShowCombineButton = rawData.CanCombine;
if (ItemType == ItemType.Weapon && rawData.WeaponData != null)
{
@@ -12,6 +12,7 @@ namespace SepCore.UI
protected override UIFormType UIFormType => UIFormType.ItemTooltipForm;
private Action<int, int> _onRecycle;
private Action<int> _onCombine;
private bool _subscribed = false;
@@ -19,7 +20,9 @@ namespace SepCore.UI
{
if (_subscribed) return;
GameEntry.Event.Subscribe(ItemTooltipRecycleEventArgs.EventId, ItemTooltipRecycle);
GameEntry.Event.Subscribe(ItemTooltipCombineEventArgs.EventId, ItemTooltipCombine);
GameEntry.Event.Subscribe(ItemTooltipHideEventArgs.EventId, ItemTooltipHide);
GameEntry.Event.Subscribe(DisplayItemLockEventArgs.EventId, DisplayItemLock);
_subscribed = true;
}
@@ -27,7 +30,9 @@ namespace SepCore.UI
{
if (!_subscribed) return;
GameEntry.Event.Unsubscribe(ItemTooltipRecycleEventArgs.EventId, ItemTooltipRecycle);
GameEntry.Event.Unsubscribe(ItemTooltipCombineEventArgs.EventId, ItemTooltipCombine);
GameEntry.Event.Unsubscribe(ItemTooltipHideEventArgs.EventId, ItemTooltipHide);
GameEntry.Event.Unsubscribe(DisplayItemLockEventArgs.EventId, DisplayItemLock);
_subscribed = false;
}
@@ -75,12 +80,14 @@ namespace SepCore.UI
}
_onRecycle = rawData.OnRecycle;
_onCombine = rawData.OnCombine;
await OpenFormAsync(context, timeout);
}
public override async UniTask CloseUIAsync(object userData = null, float timeout = 30f)
{
_onRecycle = null;
_onCombine = null;
await base.CloseUIAsync(userData, timeout);
}
@@ -94,6 +101,19 @@ namespace SepCore.UI
#region Event Handlers
private void DisplayItemLock(object sender, GameEventArgs e)
{
if (e is not DisplayItemLockEventArgs)
{
return;
}
if (Form != null && Form.Visible)
{
Form.SetMaskEnabled(true);
}
}
private void ItemTooltipRecycle(object sender, GameEventArgs e)
{
if (e is not ItemTooltipRecycleEventArgs args)
@@ -104,6 +124,16 @@ namespace SepCore.UI
_onRecycle?.Invoke(args.Index, args.Price);
}
private void ItemTooltipCombine(object sender, GameEventArgs e)
{
if (e is not ItemTooltipCombineEventArgs args)
{
return;
}
_onCombine?.Invoke(args.Index);
}
private void ItemTooltipHide(object sender, GameEventArgs e)
{
if (e is not ItemTooltipHideEventArgs args) return;
@@ -1,4 +1,5 @@
using UnityEngine;
using SepCore.Event;
using UnityGameFramework.Runtime;
namespace SepCore.UI
@@ -14,10 +15,16 @@ namespace SepCore.UI
private ItemTooltipContext _context;
private Vector3 _targetPos;
public void SetMaskEnabled(bool enabled)
{
View.maskImage.enabled = enabled;
}
public void RefreshUI(ItemTooltipContext context)
{
_context = context;
_targetPos = ConvertWorldToAnchored(_context.TargetPos);
View.maskImage.enabled = false;
foreach (RarityPanel panel in _rarityPanels)
{
@@ -54,6 +61,7 @@ namespace SepCore.UI
protected override void OnClose(bool isShutdown, object userData)
{
View.maskImage.enabled = false;
_context = null;
base.OnClose(isShutdown, userData);
}
@@ -7,6 +7,7 @@ namespace SepCore.UI
public partial class ItemTooltipView : MonoBehaviour
{
[SerializeField] public global::UnityEngine.RectTransform contentRectTransform;
[SerializeField] public global::UnityEngine.UI.Image maskImage;
[SerializeField] public global::SepCore.UI.ItemBasicTooltipForm basicForm;
[SerializeField] public global::SepCore.UI.ItemDetailTooltipForm detailForm;
}
@@ -30,6 +30,7 @@ namespace SepCore.UI
GameEntry.Event.Subscribe(DisplayItemHoverEventArgs.EventId, DisplayItemHover);
GameEntry.Event.Subscribe(DisplayItemLockEventArgs.EventId, DisplayItemLock);
GameEntry.Event.Subscribe(DisplayItemHideEventArgs.EventId, DisplayItemHide);
GameEntry.Event.Subscribe(ItemTooltipHideEventArgs.EventId, ItemTooltipHide);
GameEntry.Event.Subscribe(PlayerCoinChangeEventArgs.EventId, PlayerCoinChange);
GameEntry.Event.Subscribe(OpenUIFormSuccessEventArgs.EventId, OpenUIFormComplete);
}
@@ -42,6 +43,7 @@ namespace SepCore.UI
GameEntry.Event.Unsubscribe(DisplayItemHoverEventArgs.EventId, DisplayItemHover);
GameEntry.Event.Unsubscribe(DisplayItemLockEventArgs.EventId, DisplayItemLock);
GameEntry.Event.Unsubscribe(DisplayItemHideEventArgs.EventId, DisplayItemHide);
GameEntry.Event.Unsubscribe(ItemTooltipHideEventArgs.EventId, ItemTooltipHide);
GameEntry.Event.Unsubscribe(PlayerCoinChangeEventArgs.EventId, PlayerCoinChange);
GameEntry.Event.Unsubscribe(OpenUIFormSuccessEventArgs.EventId, OpenUIFormComplete);
}
@@ -184,6 +186,7 @@ namespace SepCore.UI
return false;
}
bool canCombine = _useCase.CanCombineWeapon(index, out _, out _);
rawData = new ItemTooltipRawData
{
TargetPos = targetPos,
@@ -193,6 +196,8 @@ namespace SepCore.UI
ItemType = ItemType.Weapon,
Price = _useCase.CalculateRecyclePrice(weapon.WeaponData.Price),
OnRecycle = RecycleWeapon,
CanCombine = canCombine,
OnCombine = CombineWeapon,
LastWaveDamage = weapon.WeaponData.LastWaveDamage,
CurrentTagCounts = GetEquippedTagCounts(),
};
@@ -272,13 +277,40 @@ namespace SepCore.UI
return;
}
int currentCount = Mathf.Max(0, Context.WeaponListContext.CurrentCount - 1);
Context.WeaponListContext.CurrentCount = currentCount;
Context.WeaponListContext = BuildDisplayListContext(DisplayListAreaType.Weapon, _rawData.WeaponItems, _rawData.WeaponMaxCount);
Context.NeedRefreshWeaponList = true;
Context.StatContext = BuildStatContext(_useCase.CreateStatRawData());
Context.NeedRefreshStat = true;
RefreshUI(Form, Context);
_tooltipLocked = false;
GameEntry.UIRouter.CloseUIAsync(UIFormType.ItemTooltipForm).Forget();
}
private void CombineWeapon(int index)
{
OnCombineWeaponAsync(index).Forget();
}
private async UniTaskVoid OnCombineWeaponAsync(int index)
{
if (_useCase == null || Context == null)
{
Log.Error("ShopController.OnCombineWeaponAsync() controller state is invalid.");
return;
}
bool success = await _useCase.TryCombineWeaponAsync(index);
if (!success)
{
return;
}
Context.WeaponListContext = BuildDisplayListContext(DisplayListAreaType.Weapon, _rawData.WeaponItems, _rawData.WeaponMaxCount);
Context.NeedRefreshWeaponList = true;
Context.StatContext = BuildStatContext(_useCase.CreateStatRawData());
Context.NeedRefreshStat = true;
RefreshUI(Form, Context);
_tooltipLocked = false;
GameEntry.UIRouter.CloseUIAsync(UIFormType.ItemTooltipForm).Forget();
}
@@ -394,6 +426,13 @@ namespace SepCore.UI
RefreshUI(Form, Context);
}
private void ItemTooltipHide(object sender, GameEventArgs e)
{
if (e is not ItemTooltipHideEventArgs) return;
_tooltipLocked = false;
}
private void OpenUIFormComplete(object sender, GameEventArgs e)
{
if (e is not OpenUIFormSuccessEventArgs ne) return;
@@ -23,6 +23,7 @@ namespace SepCore.DebugPanel
private const float CornerTapWindow = 0.6f;
private const int RequiredCornerTapCount = 3;
private const int DebugHealAmount = 200;
private const string PlayerHealthChildKey = "Health";
[Header("Window Content")]
[SerializeField] private bool _showBuffSection = true;
@@ -235,7 +236,7 @@ namespace SepCore.DebugPanel
GUILayout.Label("Battle Debug");
ProcedureGame procedure = GameEntry.Procedure.CurrentProcedure as ProcedureGame;
Player player = FindPlayer();
HealthComponent playerHealth = player != null ? player.GetComponent<HealthComponent>() : null;
HealthComponent playerHealth = GetPlayerHealth(player);
if (procedure == null)
{
@@ -440,12 +441,39 @@ namespace SepCore.DebugPanel
Player player = FindPlayer();
if (player == null) return;
HealthComponent playerHealth = player.GetComponent<HealthComponent>();
HealthComponent playerHealth = GetPlayerHealth(player);
if (playerHealth == null) return;
RestorePlayerHealthToMax(playerHealth);
}
private static HealthComponent GetPlayerHealth(Player player)
{
if (player == null)
{
return null;
}
ChildrenMap childrenMap = player.GetComponent<ChildrenMap>();
if (childrenMap != null)
{
GameObject healthObject = childrenMap.Get(PlayerHealthChildKey);
if (healthObject != null)
{
HealthComponent healthComponent = healthObject.GetComponent<HealthComponent>();
if (healthComponent != null)
{
return healthComponent;
}
}
}
return player.GetComponent<HealthComponent>();
}
private static void AddPlayerHealth(HealthComponent playerHealth, int amount)
{
if (playerHealth == null) return;
if (amount <= 0) return;
if (playerHealth.CurrentHealth <= 0) return;
@@ -461,6 +489,7 @@ namespace SepCore.DebugPanel
private static void RestorePlayerHealthToMax(HealthComponent playerHealth)
{
if (playerHealth == null) return;
if (playerHealth.CurrentHealth <= 0) return;
int maxHealth = playerHealth.MaxHealth;
@@ -472,6 +501,7 @@ namespace SepCore.DebugPanel
private static void PublishPlayerHealthChanged(HealthComponent playerHealth)
{
if (playerHealth == null) return;
GameEntry.Event.Fire(null,
PlayerHealthChangeEventArgs.Create(0, playerHealth.CurrentHealth, playerHealth.MaxHealth));
}
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Cysharp.Threading.Tasks;
using SepCore.Definition;
using SepCore.Entity;
@@ -24,6 +25,7 @@ namespace SepCore.Procedure
public override bool UseNativeDialog => false;
private PlayerData _currentPlayerData;
private CancellationTokenSource _entryCancellation;
public int CurrentLevel = 1;
private GameStateType _currentGameState = GameStateType.None;
@@ -89,7 +91,8 @@ namespace SepCore.Procedure
CurrentLevel = 1;
_currentPlayerData = new PlayerData(-1);
EnterAsync(procedureOwner).Forget();
_entryCancellation = new CancellationTokenSource();
EnterAsync(procedureOwner, _entryCancellation.Token).Forget();
}
protected override void OnUpdate(IFsm<IProcedureManager> procedureOwner, float elapseSeconds,
@@ -101,6 +104,9 @@ namespace SepCore.Procedure
protected override void OnLeave(IFsm<IProcedureManager> procedureOwner, bool isShutdown)
{
_entryCancellation.Cancel();
_entryCancellation.Dispose();
if (_gameStates != null)
{
foreach (var state in _gameStates.Values)
@@ -109,8 +115,11 @@ namespace SepCore.Procedure
}
_gameStates.Clear();
_gameStates = null;
}
_currentGameState = GameStateType.None;
GameEntry.UIRouter.CloseUIAsync(UIFormType.HudForm).Forget();
GameEntry.CameraModule?.SetTarget(null);
@@ -122,21 +131,34 @@ namespace SepCore.Procedure
#endregion
private async UniTaskVoid EnterAsync(IFsm<IProcedureManager> procedureOwner)
private async UniTaskVoid EnterAsync(IFsm<IProcedureManager> procedureOwner,
CancellationToken cancellationToken)
{
try
{
Player = await GameEntry.Entity.ShowPlayerAsync(_currentPlayerData);
Player player = await GameEntry.Entity.ShowPlayerAsync(_currentPlayerData);
if (cancellationToken.IsCancellationRequested)
{
GameEntry.Entity.HideEntity(player);
return;
}
Player = player;
GameEntry.CameraModule?.SetTarget(Player != null ? Player.CachedTransform : null);
await GameEntry.UIRouter.OpenUIAsync(UIFormType.HudForm);
cancellationToken.ThrowIfCancellationRequested();
string selectedRoleName = procedureOwner.GetData<VarString>("SelectedRoleName").Value;
var role = GameEntry.Luban.Get<RoleConfig>(selectedRoleName);
var expConfig = GameEntry.Luban.Get<LevelExperienceConfig>(selectedRoleName);
Player.InitRole(role, expConfig);
await player.InitRoleAsync(role, expConfig, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
InitGameState();
}
catch (OperationCanceledException)
{
}
catch (Exception exception)
{
Log.Error("ProcedureGame.EnterAsync() failed with exception '{0}'.", exception);
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using SepCore.Battle;
using SepCore.CustomUtility;
using SepCore.Definition;
using SepCore.Entity;
using UnityEngine;
@@ -49,7 +50,7 @@ namespace SepCore.Components
_weapons = new List<WeaponBase>(WeaponCapacity);
_props = new List<PropItem>();
_statComponent = GetComponent<StatComponent>();
_statComponent = player.StatComponent;
_synergyManager.Initialize();
}
@@ -76,12 +77,64 @@ namespace SepCore.Components
if (result)
{
GameEntry.Entity.DetachEntity(weapon.Id, _player.Id);
RealignWeaponSlots();
_synergyManager.RefreshSynergies(_weapons, _statComponent.Pipeline);
}
return result;
}
public void RealignWeaponSlots()
{
if (_weaponSlots == null || _player == null) return;
for (int i = 0; i < _weapons.Count; i++)
{
if (i < _weaponSlots.Length && _weapons[i] != null)
{
GameEntry.Entity.AttachEntity(_weapons[i].Id, _player.Id, _weaponSlots[i]);
}
}
}
public bool CanCombineWeapon(int index, out int matchIndex, out WeaponConfig nextTierConfig)
{
matchIndex = -1;
nextTierConfig = null;
if (_weapons == null || index < 0 || index >= _weapons.Count)
{
return false;
}
WeaponBase target = _weapons[index];
if (target?.WeaponData == null)
{
return false;
}
if (!WeaponUtility.TryGetNextTierConfig(target.WeaponData.Config, out nextTierConfig))
{
return false;
}
for (int i = 0; i < _weapons.Count; i++)
{
if (i == index) continue;
WeaponBase other = _weapons[i];
if (other?.WeaponData == null) continue;
if (other.WeaponData.WeaponType == target.WeaponData.WeaponType &&
other.WeaponData.Rarity == target.WeaponData.Rarity)
{
matchIndex = i;
return true;
}
}
return false;
}
public bool AttachProp(PropItem prop)
{
_props.Add(prop);
@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityGameFramework.Runtime;
namespace SepCore.Components
{
[DisallowMultipleComponent]
public class ChildrenMap : MonoBehaviour
{
[Serializable]
public class Entry
{
[SerializeField] private string _key = string.Empty;
[SerializeField] private GameObject _target = null;
public string Key => _key;
public GameObject Target => _target;
public Entry()
{
}
public Entry(string key, GameObject target)
{
_key = key;
_target = target;
}
}
[SerializeField] private List<Entry> _entries = new List<Entry>();
private Dictionary<string, GameObject> _map;
private void Awake()
{
InitMap();
}
public GameObject Get(string key)
{
if (_map == null)
{
InitMap();
}
if (string.IsNullOrEmpty(key))
{
Log.Error("[ChildrenMap] Key is null or empty when getting child on '{0}'.", gameObject.name);
return null;
}
if (!_map.TryGetValue(key, out GameObject target))
{
Log.Error("[ChildrenMap] Key '{0}' not found on '{1}'.", key, gameObject.name);
return null;
}
if (target == null)
{
Log.Error("[ChildrenMap] Target GameObject for key '{0}' is null on '{1}'.", key, gameObject.name);
return null;
}
return target;
}
private void InitMap()
{
if (_map != null)
{
return;
}
_map = new Dictionary<string, GameObject>(_entries.Count);
for (int i = 0; i < _entries.Count; i++)
{
Entry entry = _entries[i];
if (entry == null)
{
continue;
}
if (string.IsNullOrEmpty(entry.Key))
{
Log.Error("[ChildrenMap] Key is null or empty on '{0}'.", gameObject.name);
continue;
}
if (_map.ContainsKey(entry.Key))
{
Log.Error("[ChildrenMap] Duplicate key '{0}' on '{1}'.", entry.Key, gameObject.name);
continue;
}
_map.Add(entry.Key, entry.Target);
}
}
#if UNITY_EDITOR
private void OnValidate()
{
if (_entries == null)
{
return;
}
var seenKeys = new HashSet<string>();
for (int i = 0; i < _entries.Count; i++)
{
Entry entry = _entries[i];
if (entry == null || string.IsNullOrEmpty(entry.Key))
{
continue;
}
if (!seenKeys.Add(entry.Key))
{
Debug.LogWarning($"[ChildrenMap] Duplicate key '{entry.Key}' detected on '{gameObject.name}'.", this);
}
}
}
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fb474f3f35451124b830a5d5cf7b367c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -37,16 +37,9 @@ namespace SepCore.Components
_cachedTransform = target;
_direction = Vector3.forward;
_avoidEnemyOverlap = avoidEnemyOverlap;
float defaultRadius = GameEntry.Luban != null && GameEntry.Luban.IsReady
? GameEntry.Luban.Global.EnemyBodyRadius / 1000f
: 0.5f;
int defaultIterations = GameEntry.Luban != null && GameEntry.Luban.IsReady
? GameEntry.Luban.Global.EnemySeparationIterations
: 4;
_enemyBodyRadius = Mathf.Max(0.01f, enemyBodyRadius ?? defaultRadius);
_separationIterations = Mathf.Max(1, separationIterations ?? defaultIterations);
_enemyBodyRadius = GameEntry.Luban.Global.EnemyBodyRadius;
_separationIterations = GameEntry.Luban.Global.EnemySeparationIterations;
TryGetComponent(out _player);
TryGetComponent(out _enemy);
@@ -0,0 +1,111 @@
using SepCore.Definition;
using UnityEngine;
namespace SepCore.Components
{
public class PlayerMovementComponent : MonoBehaviour
{
private static readonly int WalkStateHash = Animator.StringToHash("Base Layer.Walk");
[SerializeField] private Transform _model = null;
[SerializeField] private Animator _animator = null;
[SerializeField] private float _turnSpeed = 720f;
private Transform _target;
private StatComponent _statComponent;
private Vector3 _direction;
private Quaternion _initialModelRotation = Quaternion.identity;
private bool _canMove;
private bool _isWalking;
public float Speed => _statComponent.GetStatValue(StatType.MoveSpeed);
public Vector3 Direction => _direction;
public bool IsMoving => _isWalking;
public void OnInit(float speed, Transform target, StatComponent statComponent)
{
_target = target;
_statComponent = statComponent;
_statComponent.Pipeline.SetBaseValue(StatType.MoveSpeed, speed);
_initialModelRotation = _model.localRotation;
_direction = Vector3.zero;
_canMove = false;
_isWalking = false;
_animator.applyRootMotion = false;
_animator.Rebind();
ResetWalkPose();
}
public void SetMove(bool canMove)
{
_canMove = canMove;
if (!canMove)
{
_direction = Vector3.zero;
SetWalking(false);
}
}
public void SetDirection(Vector3 direction)
{
direction.y = 0f;
_direction = Vector3.ClampMagnitude(direction, 1f);
}
public void OnUpdate(float elapseSeconds, float realElapseSeconds)
{
if (!_canMove || elapseSeconds <= 0f)
{
return;
}
float speed = Speed;
bool walking = speed > 0f && _direction.sqrMagnitude > Mathf.Epsilon;
SetWalking(walking);
if (!walking)
{
return;
}
_target.position += _direction * (speed * elapseSeconds);
Quaternion rotation = Quaternion.LookRotation(_direction, Vector3.up);
_model.rotation = Quaternion.RotateTowards(_model.rotation, rotation, _turnSpeed * elapseSeconds);
}
public void OnReset()
{
_canMove = false;
_isWalking = false;
_direction = Vector3.zero;
_target = null;
_statComponent = null;
_model.localRotation = _initialModelRotation;
ResetWalkPose();
}
private void SetWalking(bool walking)
{
if (_isWalking == walking)
{
return;
}
_isWalking = walking;
if (walking)
{
_animator.speed = 1f;
}
else
{
ResetWalkPose();
}
}
private void ResetWalkPose()
{
_animator.speed = 0f;
_animator.Play(WalkStateHash, 0, 0f);
_animator.Update(0f);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a9366dc6d1e945058db4c74cb557ae41
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,128 @@
using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using SepCore.AsyncTask;
using SepCore.CustomUtility;
using SepCore.Definition;
using UnityEngine;
using UnityGameFramework.Runtime;
namespace SepCore.Components
{
public class SkinComponent : MonoBehaviour
{
private static readonly int BaseMapPropertyId = Shader.PropertyToID("_BaseMap");
private MeshRenderer[] _renderers;
private Material _instanceMaterial;
private Texture2D _loadedTexture;
private int _generation;
public async UniTask OnInitAsync(RoleConfig role, CancellationToken cancellationToken = default)
{
int generation = ++_generation;
EnsureRenderersAndMaterial();
SetRenderersVisible(false);
_instanceMaterial.SetTexture(BaseMapPropertyId, null);
ReleaseLoadedTexture();
cancellationToken.ThrowIfCancellationRequested();
string textureAssetName = AssetUtility.GetSpriteAsset(role.Texture_Ref.AtlasPath);
Texture2D texture;
try
{
texture = await GameEntry.Resource.LoadAssetAsync<Texture2D>(textureAssetName);
}
catch (Exception exception) when (!(exception is OperationCanceledException))
{
Log.Error("SkinComponent.OnInitAsync: Failed to load skin texture '{0}'. {1}", textureAssetName,
exception.Message);
throw;
}
if (generation != _generation || cancellationToken.IsCancellationRequested)
{
GameEntry.Resource.UnloadAsset(texture);
throw new OperationCanceledException(cancellationToken);
}
_loadedTexture = texture;
_instanceMaterial.SetTexture(BaseMapPropertyId, _loadedTexture);
SetRenderersVisible(true);
}
public void OnReset()
{
_generation++;
if (_renderers != null)
{
SetRenderersVisible(false);
}
if (_instanceMaterial != null)
{
_instanceMaterial.SetTexture(BaseMapPropertyId, null);
}
ReleaseLoadedTexture();
}
private void OnDestroy()
{
OnReset();
if (_instanceMaterial == null)
{
return;
}
if (Application.isPlaying)
{
Destroy(_instanceMaterial);
}
else
{
DestroyImmediate(_instanceMaterial);
}
_instanceMaterial = null;
}
private void EnsureRenderersAndMaterial()
{
if (_renderers != null)
{
return;
}
_renderers = GetComponentsInChildren<MeshRenderer>(true);
_instanceMaterial = new Material(_renderers[0].sharedMaterial);
for (int i = 0; i < _renderers.Length; i++)
{
_renderers[i].sharedMaterial = _instanceMaterial;
}
}
private void SetRenderersVisible(bool visible)
{
for (int i = 0; i < _renderers.Length; i++)
{
_renderers[i].enabled = visible;
}
}
private void ReleaseLoadedTexture()
{
if (_loadedTexture == null)
{
return;
}
GameEntry.Resource.UnloadAsset(_loadedTexture);
_loadedTexture = null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6f3d7be5910a4a0499f0a5cf0f870e96
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -7,6 +7,7 @@ using SepCore.Definition;
using SepCore.Entity;
using SepCore.CustomUtility;
using SepCore.AsyncTask;
using UnityGameFramework.Runtime;
namespace SepCore.Entity
{
@@ -15,10 +16,11 @@ namespace SepCore.Entity
protected override TargetableObjectData _targetableObjectData => _playerData;
private InputComponent _inputComponent;
private MovementComponent _movementComponent;
private PlayerMovementComponent _movementComponent;
private AbsorbComponent _absorbComponent;
private StatComponent _statComponent;
private BackpackComponent _backpackComponent;
private SkinComponent _skinComponent;
private PlayerData _playerData;
/// <summary>
@@ -135,6 +137,47 @@ namespace SepCore.Entity
return true;
}
public bool CanCombineWeapon(int index, out int matchIndex, out WeaponConfig nextTierConfig)
{
return _backpackComponent.CanCombineWeapon(index, out matchIndex, out nextTierConfig);
}
public async UniTask<WeaponBase> CombineWeaponsAsync(WeaponBase weaponA, WeaponBase weaponB, WeaponConfig nextTierConfig, float? timeout = null)
{
if (weaponA == null || weaponB == null || nextTierConfig == null)
{
return null;
}
using (_statComponent.Pipeline.BeginBatchUpdate())
{
_backpackComponent.DetachWeapon(weaponA);
GameEntry.Entity.HideEntity(weaponA);
_backpackComponent.DetachWeapon(weaponB);
GameEntry.Entity.HideEntity(weaponB);
int id = GameEntry.Entity.NextId();
var weaponData = EntityDataFactory.Create(id, nextTierConfig, Id, CampType.Player);
float actualTimeout = timeout ?? (GameEntry.Luban.Global.EntityAsyncTimeout / 1000f);
WeaponBase newWeapon = await GameEntry.Entity.ShowWeaponAsync(weaponData, actualTimeout);
if (newWeapon == null)
{
Log.Error("Player.CombineWeaponsAsync: Failed to show new weapon {0}.", nextTierConfig.Id);
return null;
}
if (!_backpackComponent.AttachWeapon(newWeapon))
{
GameEntry.Entity.HideEntity(newWeapon);
return null;
}
return newWeapon;
}
}
public bool Enable
{
get => _enable;
@@ -156,11 +199,13 @@ namespace SepCore.Entity
_backpackComponent.SetWeaponState(_enable && _weaponEnabled);
}
public void InitRole(RoleConfig role, LevelExperienceConfig expConfig)
public async UniTask InitRoleAsync(RoleConfig role, LevelExperienceConfig expConfig,
CancellationToken cancellationToken = default)
{
// MovementComponent
await _skinComponent.OnInitAsync(role, cancellationToken);
// PlayerMovementComponent
_movementComponent.OnInit(role.Speed, this.CachedTransform, _statComponent);
_movementComponent.SetMove(true);
// HealthComponent
_healthComponent.OnInit(role.MaxHealth, _statComponent);
@@ -168,7 +213,6 @@ namespace SepCore.Entity
// BackpackComponent
Coin = role.Coin;
_backpackComponent.OnInit(this);
AddWeaponAsync(EntityDataFactory.Create(GameEntry.Entity.NextId(), WeaponType.Knife, Id, _playerData.Camp)).Forget();
// StatComponent
foreach (var modifier in role.StatModifierConfigs)
@@ -178,6 +222,8 @@ namespace SepCore.Entity
_expRequires = expConfig.ToTargetLevelArray();
await AddWeaponAsync(EntityDataFactory.Create(GameEntry.Entity.NextId(), WeaponType.Knife, Id, _playerData.Camp));
// Fire Events
GameEntry.Event.Fire(this,
PlayerHealthChangeEventArgs.Create(0, _healthComponent.CurrentHealth, _healthComponent.MaxHealth));
@@ -198,11 +244,14 @@ namespace SepCore.Entity
{
base.OnInit(userData);
_inputComponent = GetComponent<InputComponent>();
_movementComponent = GetComponent<MovementComponent>();
_absorbComponent = GetComponent<AbsorbComponent>();
_statComponent = GetComponent<StatComponent>();
_backpackComponent = GetComponent<BackpackComponent>();
ChildrenMap childrenMap = GetComponent<ChildrenMap>();
_inputComponent = childrenMap.Get("Input").GetComponent<InputComponent>();
_movementComponent = childrenMap.Get("Movement").GetComponent<PlayerMovementComponent>();
_healthComponent = childrenMap.Get("Health").GetComponent<HealthComponent>();
_absorbComponent = childrenMap.Get("Absorb").GetComponent<AbsorbComponent>();
_statComponent = childrenMap.Get("Stat").GetComponent<StatComponent>();
_backpackComponent = childrenMap.Get("Backpack").GetComponent<BackpackComponent>();
_skinComponent = childrenMap.Get("Skin").GetComponent<SkinComponent>();
}
protected override void OnShow(object userData)
@@ -217,9 +266,10 @@ namespace SepCore.Entity
}
_inputComponent.OnInit();
_inputComponent.SetListening(true);
_inputComponent.SetListening(false);
_absorbComponent.OnInit(this);
_weaponEnabled = true;
_enable = false;
_currentLevel = 0;
}
@@ -229,6 +279,7 @@ namespace SepCore.Entity
base.OnUpdate(elapseSeconds, realElapseSeconds);
_movementComponent.SetDirection(_inputComponent.Direction);
_movementComponent.OnUpdate(elapseSeconds, realElapseSeconds);
_absorbComponent.OnUpdate(elapseSeconds, realElapseSeconds);
}
@@ -240,6 +291,7 @@ namespace SepCore.Entity
_statComponent.OnReset();
_backpackComponent.OnReset();
_absorbComponent.OnReset();
_skinComponent.OnReset();
base.OnHide(isShutdown, userData);
}
@@ -23,6 +23,8 @@ namespace SepCore.UI
public int Price;
public Vector3 TargetPos;
public Action<int, int> OnRecycle;
public bool CanCombine;
public Action<int> OnCombine;
public int LastWaveDamage;
public IReadOnlyDictionary<WeaponTag, int> CurrentTagCounts;
}
@@ -351,5 +351,26 @@ namespace SepCore.UI
{
return Mathf.FloorToInt(basePrice * GameEntry.Luban.Global.WeaponRecycleRate);
}
public bool CanCombineWeapon(int index, out int matchIndex, out WeaponConfig nextTierConfig)
{
return _player.CanCombineWeapon(index, out matchIndex, out nextTierConfig);
}
public async UniTask<bool> TryCombineWeaponAsync(int index)
{
if (!_player.CanCombineWeapon(index, out int matchIndex, out WeaponConfig nextTierConfig))
{
Log.Warning("ShopUseCase.TryCombineWeaponAsync: Cannot combine weapon at index {0}.", index);
return false;
}
var weapons = _player.Weapons;
WeaponBase weaponA = weapons[index];
WeaponBase weaponB = weapons[matchIndex];
WeaponBase newWeapon = await _player.CombineWeaponsAsync(weaponA, weaponB, nextTierConfig);
return newWeapon != null;
}
}
}