InstanceUnit.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using CommonAI.RTS;
  5. using CommonLang.Vector;
  6. using CommonAI.Zone;
  7. using CommonAI.Zone.Instance;
  8. using CommonAI.RTS.Manhattan;
  9. using CommonLang;
  10. using CommonLang.Log;
  11. using CommonAI.Zone.Formula;
  12. using CommonAI.ZoneClient;
  13. using CommonAI.Zone.Helper;
  14. using CommonLang.Property;
  15. using CommonAI.Zone.Attributes;
  16. using CommonAI.Zone.EventTrigger;
  17. using CommonAI.Zone.Instance.Helper;
  18. using CommonAI.Data;
  19. using static CommonAI.Zone.UnitInfo;
  20. using CommonAI.data;
  21. namespace CommonAI.Zone.Instance
  22. {
  23. abstract public partial class InstanceUnit : InstanceZoneObject
  24. {
  25. private readonly UnitInfo mInfo;
  26. private readonly DropItemGenerator mDropItems;
  27. /// <summary>
  28. /// 统计信息
  29. /// </summary>
  30. public IUnitStatistic Statistic { get; private set; }
  31. //最后一次受伤时间
  32. public long mLastDamageTime;
  33. //最后一次攻击事件
  34. public long mLastHitOtherTime;
  35. //上一次处理死亡回调时间
  36. public long mProcessDeadCallbackTime;
  37. private IFormula mFormula = TemplateManager.Factory.Formula;
  38. private IVirtualUnit mUnitVirtual;
  39. private readonly string mName;
  40. private int mForce = 0;
  41. private int mAlliesForce = 0; // 服务器对战情况下,有盟友服务器
  42. private int mLevel = 0;
  43. private int mMoney = 0;
  44. private readonly bool mIsAttackRangeIncludeBodySize;
  45. // 当前HP
  46. private readonly RangeValue __mCurrentHP;
  47. // 当前MP
  48. private readonly RangeValue __mCurrentMP;
  49. // 当前移动速度加成
  50. private float __mCurrentMoveSpeedSEC = 0;
  51. // 攻速
  52. private int __mCurrentAttackSpeed = 10000;
  53. // 当前技能速度加成
  54. private float __mSkillActionSpeedRate = 0;
  55. // 当前快速施法速度
  56. private float mFastCastRate = 0;
  57. /// <summary>
  58. /// 当前单位是否地图阻挡
  59. /// </summary>
  60. private bool mIntersectMap = false;
  61. /// <summary>
  62. /// 当前单位是否单位阻挡
  63. /// </summary>
  64. private bool mIntersectObj = false;
  65. // 当前技能cd减少
  66. private float __mCurrentSkillCdReduce;
  67. // 控制减速,韧性
  68. private float __mCurrentControledTimeReduce;
  69. // 控制增幅
  70. private float __mControledTimeAdd;
  71. /// 单位最后死亡时间
  72. private long mDeadTime = 0;
  73. //游戏服标记字段,怪物死亡的时候,回传给游戏服
  74. public int gameServerFlag = 0;
  75. //回血
  76. public int recoverHP = 0;
  77. //随从最后一次瞬移时间
  78. public long petTeleportTime = 0;
  79. //最后一次返回召回随从操作频繁时间
  80. public long lastTeleportTime = 0;
  81. //绑定攻击玩家
  82. private string mBindAttackPlayerId;
  83. //主人id
  84. private long mRemoveSelfTime;
  85. private InstanceUnit mBindMaster;
  86. /// <summary>
  87. /// 自动恢复计数器
  88. /// </summary>
  89. private TimeInterval<int> mRecoveryTime = null;
  90. public InstanceUnit(InstanceZone zone, UnitInfo uinfo, string name, int force, int level, bool is_static_block = false, int alliesForce = 0)
  91. : base(zone, is_static_block)
  92. {
  93. this.mInfo = (UnitInfo)uinfo.Clone();
  94. this.mName = string.IsNullOrEmpty(name) ? "" : name;
  95. this.mIsAttackRangeIncludeBodySize = zone.Templates.CFG.OBJECT_ATTACK_RANGE_INCLUDE_BODYSIZE;
  96. this.mForce = force;
  97. this.mAlliesForce = alliesForce;
  98. this.mLevel = level;
  99. this.mIntersectMap = true;
  100. this.mIntersectObj = !Templates.CFG.OBJECT_NONE_TOUCH && (mInfo.BodySize > 0);
  101. this.mSyncInfo = new SyncUnitInfo(zone.IsHalfSync);
  102. this.mSyncInfo.Name = mName;
  103. this.mSyncInfo.TemplateID = mInfo.ID;
  104. this.__mCurrentHP = new RangeValue(mInfo.HealthPoint, 0, mInfo.HealthPoint);
  105. this.__mCurrentMP = new RangeValue(mInfo.ManaPoint, 0, mInfo.ManaPoint);
  106. this.__mCurrentMoveSpeedSEC = mInfo.MoveSpeedSEC;
  107. this.mDropItems = new DropItemGenerator(uinfo.DropItemsSet);
  108. this.mTriggerHelper = new UnitTriggerHelper(this);
  109. if (mInfo.IdleRecover && mInfo.RecoveryIntervalMS > 0)
  110. {
  111. this.mRecoveryTime = new TimeInterval<int>(mInfo.RecoveryIntervalMS);
  112. this.recoverHP = Info.HealthRecoveryPoint;
  113. }
  114. this.InitTimeLines();
  115. this.InitBagSlots();
  116. this.InitSkills(mInfo.BaseSkillID, mInfo.Skills.ToArray());
  117. this.Statistic = this.CreateUnitStatistic();
  118. this.mUnitVirtual = TemplateManager.Factory.CreateUnitVirtual(this);
  119. }
  120. protected override void Disposing()
  121. {
  122. if (mUnitVirtual != null)
  123. {
  124. mUnitVirtual.OnDispose(this);
  125. }
  126. base.Disposing();
  127. this.clearBindEvents();
  128. this.clearSkills();
  129. this.clearBuffs();
  130. this.clearItemSlots();
  131. this.clearTriggers();
  132. }
  133. protected override void onAdded(bool pointLv)
  134. {
  135. if (this.mUnitVirtual != null)
  136. {
  137. this.mUnitVirtual.OnInit(this, pointLv);
  138. if (this.mRecoveryTime != null && this.Info.UType == UnitType.TYPE_MONSTER)
  139. {
  140. this.recoverHP = Info.HealthRecoveryPoint == 0 ? (int)(this.MaxHP * 0.005f) : Info.HealthRecoveryPoint;
  141. }
  142. }
  143. this.mSyncInfo.ObjectID = base.ID;
  144. this.mSyncInfo.IsTouchObj = this.mIntersectObj;
  145. this.mSyncInfo.IsTouchMap = this.mIntersectMap;
  146. this.mSyncInfo.IsStaticBlockable = this.IsStaticBlockable;
  147. this.mSyncInfo.fateType = (byte)this.Virtual.GetUnitFateType();
  148. if (mInfo.SpawnTimeMS > 0)
  149. {
  150. this.SetInvincibleTimeMS(mInfo.SpawnTimeMS);
  151. }
  152. if (this.mInfo.InventoryList != null)
  153. {
  154. foreach (InventoryItem item in mInfo.InventoryList)
  155. {
  156. ItemTemplate temp = Templates.getItem(item.ItemTemplateID);
  157. if (temp != null)
  158. {
  159. AddItemToEmptyInventory(temp, item.Count);
  160. }
  161. }
  162. }
  163. if (mInfo.Events != null)
  164. {
  165. foreach (int evt_id in mInfo.Events)
  166. {
  167. this.BindUnitEvent(evt_id);
  168. }
  169. }
  170. if (mOnAdded != null)
  171. {
  172. mOnAdded.Invoke(this);
  173. }
  174. }
  175. protected override void onRemoved()
  176. {
  177. if (mOnRemoved != null)
  178. {
  179. mOnRemoved.Invoke(this);
  180. }
  181. foreach (UnitEventTriggerCollection uc in mBindEvents.Values)
  182. {
  183. uc.Dispose();
  184. }
  185. mBindEvents.Clear();
  186. if (Info.RemovedEffect != null)
  187. {
  188. Parent.queueEvent(new AddEffectEvent(this.ID, X, Y, Direction, Info.RemovedEffect));
  189. }
  190. }
  191. public void BindAttackPlayer(string playerId)
  192. {
  193. this.mBindAttackPlayerId = playerId;
  194. }
  195. public string GetAttackPlayer()
  196. {
  197. return this.mBindAttackPlayerId;
  198. }
  199. public void BindMasterId(int masterId)
  200. {
  201. InstanceUnit master = this.Parent.getUnitByID(masterId);
  202. if(master == null)
  203. {
  204. log.Error("BindMasterId找不到单位:" + this.Parent.GetSceneID() + ", " + masterId);
  205. return;
  206. }
  207. if(this.mBindMaster != null)
  208. {
  209. log.Error("BindMasterId重复:" + this.Info.ID + ", " + master.PlayerUUID);
  210. return;
  211. }
  212. this.mBindMaster = master;
  213. }
  214. //--------------------------------------------------------------------------
  215. /// <summary>
  216. /// 扩展功能绑定接口
  217. /// </summary>
  218. public IVirtualUnit Virtual { get { return mUnitVirtual; } }
  219. /// <summary>
  220. /// 扩展数据
  221. /// </summary>
  222. public virtual IUnitProperties Properties { get { return mInfo.Properties; } }
  223. //--------------------------------------------------------------------------
  224. //--------------------------------------------------------------------------
  225. public UnitInfo Info { get { return mInfo; } }
  226. public string Name { get { return mName; } }
  227. public string Alias { get { return mSyncInfo.Alias; } set { if (value != null) { mSyncInfo.Alias = value; } } }
  228. public int Force { get { return mForce; } protected set { mForce = value; } }
  229. public int AlliesForce { get { return mAlliesForce; } protected set { mAlliesForce = value; } }
  230. public float MoveSpeedSEC { get { return __mCurrentMoveSpeedSEC; } }
  231. public float SkillCdReduce { get { return __mCurrentSkillCdReduce; } }
  232. public float ControledTimeReduce { get { return __mCurrentControledTimeReduce; } }
  233. public float ControledTimeAdd { get { return __mControledTimeAdd; } }
  234. public float FastCastRate { get { return mFastCastRate; } }
  235. public override float BodyBlockSize { get { return mInfo.BodySize; } }
  236. public override float BodyHitSize { get { return mInfo.BodyHitSize; } }
  237. public override float BodyHeight { get { return mInfo.BodyHeight; } }
  238. public override float Weight { get { return mInfo.Weight; } }
  239. public override bool IntersectMap { get { return mIntersectMap; } }
  240. public override bool IntersectObj { get { return mIntersectObj && IsVisible; } }
  241. public override bool Moveable { get { return mInfo.IsMoveable; } }
  242. public override bool ClientVisible { get { return true; } }
  243. public override bool SyncPos { get { return true; } }
  244. public override bool IsDead (){ return __mCurrentHP.Value <= 0; }
  245. public int DeadCount { get { return Statistic.DeadCount; } }
  246. public long LastDeadTimeMS { get { return mDeadTime; } }
  247. public bool CanWhiplashDeadBody { get { return Templates.CFG.UNIT_CAN_WHIPLASH_BODY && (LastDeadTimeMS + mInfo.DeadTimeMS > Parent.PassTimeMS); } }
  248. /// <summary>
  249. /// 是否为玩家
  250. /// </summary>
  251. virtual public bool IsPlayer { get { return false; } }
  252. virtual public bool IsMonster { get { return false; } }
  253. virtual public bool IsPet { get { return false; } }
  254. virtual public void OnUnitDead() {}
  255. /// <summary>
  256. /// 是否中立
  257. /// </summary>
  258. virtual public bool IsNature { get { return false; } }
  259. /// <summary>
  260. /// 此单位是否能被攻击并且活着
  261. /// </summary>
  262. virtual public bool IsActive { get { return (base.Enable) && (__mCurrentHP.Value > 0) /*&& !IsInvincible && IsVisible*/; } }
  263. /// <summary>
  264. /// 此单位是否可以被打到,包括鞭尸
  265. /// </summary>
  266. virtual public bool IsAttackable { get { return (base.Enable) /*&& !IsInvincible && IsVisible*/; } }
  267. /// <summary>
  268. /// 此单位是否无技能
  269. /// </summary>
  270. public bool IsNoneSkill { get { return mSkillStatus.Count == 0; } }
  271. /// <summary>
  272. /// 技能可产生位移,或者多段由服务器决定
  273. /// </summary>
  274. virtual public bool IsSkillControllableByServer { get { return true; } }
  275. /// <summary>
  276. /// 单位是否可控
  277. /// </summary>
  278. virtual public bool IsControllable { get { return IsActive && !IsStun && CurrentActionStatus != UnitActionStatus.Damage; } }
  279. /// <summary>
  280. /// 用于显示的,单位横向数据
  281. /// </summary>
  282. public ZoneClient.IUnitVisibleData VisibleInfo { get { return mSyncInfo.VisibleInfo; } }
  283. //-----------------------------------------------------------------------------------------------------//
  284. protected virtual IUnitStatistic CreateUnitStatistic()
  285. {
  286. return new UnitStatistic(this);
  287. }
  288. //-----------------------------------------------------------------------------------------------------//
  289. #region __StateMachine__
  290. private bool is_init = false;
  291. private State current_state = null;
  292. private State next_state;
  293. private Queue<State> next_state_queue = new Queue<State>();
  294. /// <summary>
  295. /// 当前状态机
  296. /// </summary>
  297. public State CurrentState { get { return current_state; } }
  298. //状态机额外数据
  299. public long chuangongTime = 0;
  300. /// <summary>
  301. /// 下一个状态
  302. /// </summary>
  303. protected State NextState { get { return next_state; } }
  304. /// <summary>
  305. /// 死亡状态可能的状态机,一般配合<see cref="IsDead"/>使用
  306. /// </summary>
  307. public bool IsStateDead
  308. {
  309. get
  310. {
  311. if ((current_state is StateDead) ||
  312. (current_state is StateDamage) ||
  313. (current_state is StateDeadFuck) ||
  314. (current_state is StateDeadFuckFuck) ||
  315. (current_state is StateRebirth) ||
  316. (next_state is StateDead) ||
  317. (next_state is StateDamage) ||
  318. (next_state is StateDeadFuck) ||
  319. (next_state is StateDeadFuckFuck) ||
  320. (next_state is StateRebirth))
  321. {
  322. return true;
  323. }
  324. return false;
  325. }
  326. }
  327. public void queueState(State s)
  328. {
  329. next_state_queue.Enqueue(s);
  330. }
  331. public bool TryEnqueueIdleState()
  332. {
  333. if (next_state_queue.Count > 0)
  334. {
  335. return false;
  336. }
  337. next_state_queue.Enqueue(new StateIdle(this));
  338. return true;
  339. }
  340. public void queueCurrentState(State s)
  341. {
  342. if (current_state != null)
  343. {
  344. if (!changeState(s))
  345. {
  346. State.StateStopHandler onstop = new State.StateStopHandler((obj, st) =>
  347. {
  348. changeState(s);
  349. });
  350. current_state.AddStopOnce(onstop);
  351. }
  352. }
  353. else
  354. {
  355. changeState(s);
  356. }
  357. }
  358. public bool changeState(State s, bool force = false)
  359. {
  360. if (s == current_state)
  361. {
  362. return true;
  363. }
  364. if (s == next_state)
  365. {
  366. return true;
  367. }
  368. if (s.unit != this)
  369. {
  370. throw new Exception("State is not Owner unit : " + s);
  371. }
  372. if (current_state == null || current_state.onBlock(s) || force)
  373. {
  374. if (next_state == null || next_state.onBlock(s) || force)
  375. {
  376. if (next_state != null)
  377. {
  378. next_state.stop();
  379. }
  380. onNewStateBeginChange(current_state, ref s);
  381. next_state = s;
  382. return true;
  383. }
  384. }
  385. return false;
  386. }
  387. private void updateState()
  388. {
  389. //绑定主人类怪物,脱战或者主人移除自杀
  390. if(mRemoveSelfTime == 0)
  391. {
  392. if (this.mBindMaster != null && (!this.mBindMaster.IsActive || this.mBindMaster.Virtual.GetBattleStatus() <= BattleStatus.ReadyBattle))
  393. {
  394. //添加移除逻辑
  395. mRemoveSelfTime = CommonLang.CUtils.localTimeMS + 3000;
  396. }
  397. }
  398. else if(mRemoveSelfTime < CommonLang.CUtils.localTimeMS)
  399. {
  400. this.kill(null, false);
  401. }
  402. if (IsDead() && (!IsStateDead))
  403. {
  404. changeState(new StateDead(this, this, false), true);
  405. Parent.cb_unitDeadCallBack(this, this);
  406. queueEvent(new UnitDeadEvent(ID, this.ID, false, mInfo.RebirthTimeMS));
  407. }
  408. else if (next_state == null && next_state_queue.Count > 0)
  409. {
  410. // 尝试从队列中取一个状态机,有机会就执行 //
  411. while (next_state_queue.Count > 0)
  412. {
  413. State queued_state = next_state_queue.Peek();
  414. if (changeState(queued_state))
  415. {
  416. next_state_queue.Dequeue();
  417. }
  418. else { break; }
  419. }
  420. }
  421. if (next_state != null && next_state != current_state)
  422. {
  423. State old_state = current_state;
  424. if (old_state != null)
  425. {
  426. old_state.stop();
  427. }
  428. this.current_state = next_state;
  429. this.next_state = null;
  430. this.current_state.start();
  431. this.onStateChanged(old_state, current_state);
  432. if (mOnStateChanged != null)
  433. {
  434. mOnStateChanged.Invoke(this, old_state, current_state);
  435. }
  436. }
  437. if (current_state != null)
  438. {
  439. current_state.update();
  440. }
  441. UpdateTimeLines(Parent.UpdateIntervalMS);
  442. }
  443. #endregion
  444. protected virtual void onUpdateRecover()
  445. {
  446. //自动恢复
  447. if (this.recoverHP > 0 && mRecoveryTime != null && this.CurrentHP < this.MaxHP && CurrentActionStatus != UnitActionStatus.Damage
  448. && this.Virtual.GetBattleStatus() == BattleStatus.None && !IsDead())
  449. {
  450. if (mRecoveryTime.Update(Parent.UpdateIntervalMS))
  451. {
  452. AddHP(this.recoverHP, null);
  453. //AddMP(Info.ManaRecoveryPoint);
  454. }
  455. }
  456. }
  457. override protected void onUpdate(bool slowRefresh)
  458. {
  459. if (!is_init)
  460. {
  461. is_init = true;
  462. onInit();
  463. }
  464. if (!IsPaused)
  465. {
  466. updatePhysical();
  467. updateState();
  468. onUpdateRecover();
  469. updateSkills();
  470. updateBuffs();
  471. updateTriggers(slowRefresh);
  472. updateItems();
  473. if (mOnUpdate != null)
  474. {
  475. mOnUpdate.Invoke(this);
  476. }
  477. }
  478. updateSyncFields();
  479. updateSyncSkillActives();
  480. }
  481. internal void doAction(ObjectAction act)
  482. {
  483. this.onAction(act);
  484. if (mOnHandleObjectAction != null)
  485. {
  486. mOnHandleObjectAction.Invoke(this, act);
  487. }
  488. }
  489. private void doRebirth(int max_hp, int max_mp)
  490. {
  491. next_state_queue.Clear();
  492. if (this.Moveable)
  493. {
  494. this.mIntersectObj = !Templates.CFG.OBJECT_NONE_TOUCH && (mInfo.BodySize > 0);
  495. }
  496. else
  497. {
  498. this.mIntersectObj = (mInfo.BodySize > 0);
  499. }
  500. if (max_hp == 0) max_hp = this.MaxHP;
  501. if (max_mp == 0) max_mp = this.MaxMP;
  502. if (max_hp != 0) this.__mCurrentHP.SetValue(max_hp);
  503. if (max_mp != 0) this.__mCurrentMP.SetValue(max_mp);
  504. syncFields(UnitFieldChangedEvent.MASK_HP | UnitFieldChangedEvent.MASK_MP);
  505. Parent.cb_unitRebirthCallBack(this);
  506. queueEvent(new UnitRebirthEvent(ID));
  507. }
  508. public void updateContinueKills()
  509. {
  510. if (this.Statistic.continueKills < short.MaxValue)
  511. {
  512. ++this.Statistic.continueKills;
  513. }
  514. UnitContinueKillValue temp = new UnitContinueKillValue(this.ID, this.Statistic.continueKills);
  515. queueEvent(temp);
  516. }
  517. public void resetContinueKills()
  518. {
  519. this.Statistic.continueKills = 0;
  520. }
  521. private void doActivated()
  522. {
  523. next_state_queue.Clear();
  524. if (this.Moveable)
  525. {
  526. this.mIntersectObj = !Templates.CFG.OBJECT_NONE_TOUCH && (mInfo.BodySize > 0);
  527. }
  528. else
  529. {
  530. this.mIntersectObj = (mInfo.BodySize > 0);
  531. }
  532. this.addTriggers(mInfo.Triggers);
  533. Parent.cb_unitActivatedCallBack(this);
  534. }
  535. internal void doDead(InstanceUnit killer)
  536. {
  537. if(killer != null)
  538. {
  539. this.Statistic.LogDead(killer.Statistic);
  540. }
  541. this.mIntersectObj = false;
  542. this.clearBuffs();
  543. //吴永辉:5v5人物死亡后会重置技能CD 无论在哪个地图死亡都不能重置 你可能要指给黄鱼 bugid=2748
  544. //this.ClearAllSkillCD();
  545. this.resetAI();
  546. }
  547. //------------------------------------------------------------------------------------------------------//
  548. internal void callback_onActivated(InstanceZone zone)
  549. {
  550. if (this.mOnActivated != null)
  551. this.mOnActivated.Invoke(this);
  552. }
  553. internal void callback_onAttack(InstanceZone zone, InstanceUnit target, int reduceHP, AttackSource source)
  554. {
  555. if (this.mOnAttack != null)
  556. this.mOnAttack(this, target, reduceHP, source);
  557. }
  558. internal void callback_onDamage(InstanceZone zone, InstanceUnit attacker, int reduceHP, AttackSource source)
  559. {
  560. if (this.mOnDamage != null)
  561. this.mOnDamage.Invoke(this, attacker, reduceHP, source);
  562. }
  563. internal void callback_onDead(InstanceZone zone, InstanceUnit attacker)
  564. {
  565. this.OnUnitDead();
  566. if (this.mOnDead != null)
  567. this.mOnDead.Invoke(this, attacker);
  568. }
  569. internal void callback_onRebirth(InstanceZone zone)
  570. {
  571. if (this.mOnRebirth != null)
  572. this.mOnRebirth.Invoke(this);
  573. }
  574. internal void callback_onGotInstanceItem(InstanceZone zone, InstanceItem item)
  575. {
  576. if (this.mOnGotInstanceItem != null)
  577. this.mOnGotInstanceItem.Invoke(this, item);
  578. }
  579. internal void callback_onGotInventoryItem(InstanceZone zone, ItemTemplate item)
  580. {
  581. if (this.mOnGotInventoryItem != null)
  582. this.mOnGotInventoryItem.Invoke(this, item);
  583. }
  584. internal void callback_onLostInventoryItem(InstanceZone zone, ItemTemplate item)
  585. {
  586. if (this.mOnLostInventoryItem != null)
  587. this.mOnLostInventoryItem.Invoke(this, item);
  588. }
  589. internal void callback_onUseItem(InstanceZone zone, ItemTemplate item, InstanceUnit item_creater)
  590. {
  591. if (this.mOnUseItem != null)
  592. this.mOnUseItem.Invoke(this, item, item_creater);
  593. }
  594. internal void callback_onGotBuff(InstanceZone zone, InstanceUnit.BuffState buff)
  595. {
  596. if (this.mOnGotBuff != null)
  597. this.mOnGotBuff.Invoke(this, buff);
  598. }
  599. internal void callback_onLostBuff(InstanceZone zone, InstanceUnit.BuffState buff)
  600. {
  601. if (this.mOnLostBuff != null)
  602. this.mOnLostBuff.Invoke(this, buff);
  603. }
  604. //-----------------------------------------------------------------------------------------------------//
  605. private void onInit()
  606. {
  607. syncFields(UnitFieldChangedEvent.MASK_ALL);
  608. if (mInfo.SpawnTimeMS > 0)
  609. {
  610. changeState(new StateSpawn(this, mInfo.SpawnTimeMS));
  611. }
  612. else
  613. {
  614. changeState(new StateIdle(this));
  615. doActivated();
  616. }
  617. }
  618. #region _Overrideable_
  619. /// <summary>
  620. /// 收到协议
  621. /// </summary>
  622. /// <param name="act"></param>
  623. virtual protected void onAction(ObjectAction act) { }
  624. /// <summary>
  625. /// 新的状态将要切换时回调
  626. /// </summary>
  627. virtual protected void onNewStateBeginChange(State old_state, ref State new_state) { }
  628. /// <summary>
  629. /// 状态已切换时回调
  630. /// </summary>
  631. /// <param name="old_state"></param>
  632. /// <param name="state"></param>
  633. virtual protected void onStateChanged(State old_state, State state) { }
  634. // 被攻击时回调
  635. virtual protected void onDamaged(InstanceUnit attacker, AttackSource source, int reduceHP) { }
  636. virtual protected void onDead(InstanceUnit killer) { }
  637. #endregion
  638. /// <summary>
  639. /// 单位被攻击核心函数,里面处理受击状态,死亡状态
  640. /// </summary>
  641. /// <param name="attacker"></param>
  642. /// <param name="source"></param>
  643. virtual protected internal void doHitAttack(InstanceUnit attacker, AttackSource source)
  644. {
  645. if (IsDead())
  646. {
  647. //死亡后鞭尸//
  648. if (Moveable && CanWhiplashDeadBody)
  649. {
  650. source.Begin(this);
  651. changeState(new StateDamage(this, source, attacker));
  652. }
  653. doHitAttackEndEffect(attacker, source);
  654. return;
  655. }
  656. else
  657. {
  658. if (current_state is StateDamage)
  659. {
  660. StateDamage state_damage = current_state as StateDamage;
  661. if (state_damage.IsDamageProtect)
  662. {
  663. return;
  664. }
  665. }
  666. // TODO HP //
  667. source.Begin(this);
  668. int reduceHP = mFormula.OnHit(attacker, source, this);
  669. // 统计 //
  670. this.Statistic.LogDamage(attacker.Statistic, reduceHP);
  671. reduceHP = this.AddHP(-reduceHP, attacker, !source.OutSendEvent, source);
  672. AttackProp attack = source.Attack;
  673. // Post Event //
  674. if (source.OutSendEvent)
  675. {
  676. UnitHitEvent evt = new UnitHitEvent(ID);
  677. evt.senderId = attacker.ID;
  678. evt.senderMasterId = attacker.Virtual.GetMasterID();
  679. evt.hp = reduceHP;
  680. evt.isDead = IsDead();
  681. evt.isCritical = source.Attack.MaskMustCritical;
  682. evt.effect = source.OutHitEffect;
  683. evt.SourceAttack = source.Attack;
  684. evt.client_state = source.OutClientState;
  685. if(source != null && attacker != null && source.FromSkillType == XmdsSkillType.cardSkill && this.IsMonster && attacker.IsMonster)
  686. {
  687. evt.InViewForceSend = true;
  688. }
  689. queueEvent(evt);
  690. }
  691. if (reduceHP > 0)
  692. {
  693. source.HasHitted = true;
  694. onDamaged(attacker, source, reduceHP);
  695. Parent.cb_unitDamageCallBack(this, attacker, reduceHP, source);
  696. if (IsDead())
  697. {
  698. doDeadProcess(attacker, source);
  699. return;
  700. }
  701. }
  702. // 非免控,才会有受击
  703. if (!this.IsIgnoreControl && source.OutIsDamage && Moveable)
  704. {
  705. changeState(new StateDamage(this, source, attacker));
  706. }
  707. doHitAttackEndEffect(attacker, source);
  708. return;
  709. }
  710. }
  711. /** 执行死亡处理逻辑 */
  712. private void doDeadProcess(InstanceUnit attacker, AttackSource source)
  713. {
  714. if (this.IsMonster)
  715. {
  716. if (this.mProcessDeadCallbackTime + 1000 > CommonLang.CUtils.localTimeMS)
  717. {
  718. log.Info("cb_unitDeadCallBack 跳过:" + this.mProcessDeadCallbackTime + ", " + this.Info.ID + ", " + this.ID);
  719. return;
  720. }
  721. if(this.Virtual.GetMaType() >= 4 && this.Level > 80)
  722. {
  723. log.Info("boss死亡:" + this.mProcessDeadCallbackTime + ", 单位id=" + this.Info.ID + ", 场景Id=" +
  724. this.Parent.GetSceneID() + ", " + this.mZone.UUID + ", " + (attacker == null ? "null" : attacker.PlayerUUID));
  725. }
  726. }
  727. mDeadTime = Parent.PassTimeMS;
  728. onDead(attacker);
  729. Parent.cb_unitDeadCallBack(this, attacker);
  730. queueEvent(new UnitDeadEvent(ID, attacker.ID, source.OutIsCrush, mInfo.RebirthTimeMS));
  731. // 被击碎,秒杀 //
  732. if (source.OutIsCrush)
  733. {
  734. Parent.queueEvent(new AddEffectEvent(this.ID, X, Y, Direction, source.Attack.CrushEffect));
  735. changeState(new StateDead(this, attacker, true));
  736. }
  737. else
  738. {
  739. if (!Moveable)
  740. {
  741. changeState(new StateDead(this, attacker));
  742. }
  743. else if (source.OutHasKnockDown || source.OutHasFly)
  744. {
  745. if (!changeState(new StateDamage(this, source, attacker)))
  746. {
  747. changeState(new StateDead(this, attacker));
  748. }
  749. }
  750. else
  751. {
  752. changeState(new StateDead(this, attacker));
  753. }
  754. }
  755. doHitAttackEndEffect(attacker, source);
  756. }
  757. /// <summary>
  758. /// 死亡后自爆或者触发法术
  759. /// </summary>
  760. /// <param name="attacker"></param>
  761. /// <param name="source"></param>
  762. private void doHitAttackEndEffect(InstanceUnit attacker, AttackSource source)
  763. {
  764. if (source.Attack.Buff != null)
  765. {
  766. AddBuff(source.Attack.Buff, attacker);
  767. }
  768. if (source.Attack.Spell != null)
  769. {
  770. Parent.attackLaunchSpell(source.FromSkillType, attacker, this, source);
  771. }
  772. }
  773. // 单位获取道具
  774. protected virtual bool tryGotItem(InstanceItem item, out bool removeItem)
  775. {
  776. if (!Parent.IsVisibleAOI(this, item))
  777. {
  778. removeItem = false;
  779. return false;
  780. }
  781. if (item.Info.DropMoneyMin > 0 && item.Info.DropMoneyMax > 0)
  782. {
  783. int min = Math.Min(item.Info.DropMoneyMin, item.Info.DropMoneyMax);
  784. int max = Math.Max(item.Info.DropMoneyMin, item.Info.DropMoneyMax);
  785. int money = RandomN.Next(min, max + 1);
  786. this.CurrentMoney += money;
  787. removeItem = item.Info.RemoveOnFinishPick;
  788. return true;
  789. }
  790. if (item.Info.GotOnUse)
  791. {
  792. // 获取后立即使用 //
  793. if (UseItem(item.Info, item.ItemCreater))
  794. {
  795. removeItem = item.Info.RemoveOnFinishPick;
  796. return true;
  797. }
  798. }
  799. else
  800. {
  801. // 获取后进背包 //
  802. if (AddItemToEmptyInventory(item.Info) > 0)
  803. {
  804. removeItem = item.Info.RemoveOnFinishPick;
  805. return true;
  806. }
  807. }
  808. removeItem = false;
  809. return false;
  810. }
  811. internal bool doGotInstanceItem(InstanceItem item, out bool removeItem, out int pickTimes)
  812. {
  813. pickTimes = 0;
  814. var ret = tryGotItem(item, out removeItem);
  815. if (ret)
  816. {
  817. pickTimes = Parent.cb_unitGotInstanceItemCallBack(this, item);
  818. if (item.Info.GotEffect != null)
  819. {
  820. queueEvent(new UnitEffectEvent(ID, item.Info.GotEffect));
  821. }
  822. }
  823. return ret;
  824. }
  825. internal void doGotInventoryItem(InventorySlot slot, ItemTemplate item, int index, int count)
  826. {
  827. mFormula.OnGotInventoryItem(this, item);
  828. queueEvent(new UnitSyncInventoryItemEvent(ID, item.ID, index, slot.Count));
  829. Parent.cb_unitGotInventoryItemCallBack(this, item, count);
  830. // 添加装备Buff //
  831. if (item.EquipBuffs != null)
  832. {
  833. foreach (LaunchBuff buff in item.EquipBuffs)
  834. {
  835. AddBuff(buff, this, true);
  836. }
  837. }
  838. }
  839. internal void doLostInventoryItem(InventorySlot slot, ItemTemplate item, int index, int count)
  840. {
  841. mFormula.OnLostInventoryItem(this, item);
  842. queueEvent(new UnitSyncInventoryItemEvent(ID, item.ID, index, slot.Count));
  843. Parent.cb_unitLostInventoryItemCallBack(this, item, count);
  844. // 移除装备Buff //
  845. if (item.EquipBuffs != null)
  846. {
  847. foreach (LaunchBuff buff in item.EquipBuffs)
  848. {
  849. removeBuff(buff.BuffID);
  850. }
  851. }
  852. }
  853. // 单位获取道具
  854. internal void doGotBuff(InstanceUnit.BuffState buff)
  855. {
  856. Parent.cb_unitGotBuffCallBack(this, buff);
  857. }
  858. internal void doLostBuff(InstanceUnit.BuffState buff)
  859. {
  860. Parent.cb_unitLostBuffCallBack(this, buff);
  861. }
  862. public bool UseItem(int itemTemplateID, InstanceUnit item_creater = null)
  863. {
  864. ItemTemplate item = Templates.getItem(itemTemplateID);
  865. if (item != null)
  866. {
  867. return UseItem(item, item_creater);
  868. }
  869. return false;
  870. }
  871. public bool UseItem(ItemTemplate item, InstanceUnit item_creater = null)
  872. {
  873. if (item_creater == null)
  874. {
  875. item_creater = this;
  876. }
  877. if (tryUseItem(item, item_creater))
  878. {
  879. beginUseItem(item);
  880. // 如果关键帧绑定特效
  881. if (item.UseEffect != null)
  882. {
  883. queueEvent(new UnitEffectEvent(ID, item.UseEffect));
  884. }
  885. // 如果关键帧绑定释放法术
  886. if (item.UseSpell != null)
  887. {
  888. Parent.unitLaunchSpell(XmdsSkillType.none, item_creater, item.UseSpell, X, Y);
  889. }
  890. if (item.UseSummon != null)
  891. {
  892. Parent.unitSummonUnit(item_creater, item.UseSummon);
  893. }
  894. // 如果关键帧绑定自己释放BUFF
  895. if (item.UseBuffs != null)
  896. {
  897. foreach (LaunchBuff buff in item.UseBuffs)
  898. {
  899. this.AddBuff(buff, item_creater);
  900. }
  901. }
  902. mFormula.OnUseItem(this, item, item_creater);
  903. queueEvent(new UnitUseItemEvent(ID, item.ID));
  904. Parent.cb_unitUseItemCallBack(this, item, item_creater);
  905. Statistic.LogUseItem(item);
  906. return true;
  907. }
  908. return false;
  909. }
  910. //-----------------------------------------------------------------------------------------------------//
  911. /// <summary>
  912. /// 有伤害源的扣血
  913. /// </summary>
  914. /// <param name="hp"></param>
  915. /// <param name="attacker"></param>
  916. /// <param name="sendHit"></param>
  917. /// <param name="hitMessage"></param>
  918. public int ReduceHP(int hp, InstanceUnit attacker, bool sendHit = true, UnitHitEvent hitMessage = null,
  919. bool IngoreHealEffect = false, DamageSource dmgSrc = DamageSource.Def)
  920. {
  921. //目标无敌,不扣血
  922. if (IsDead() || hp == 0 || ( hp > 0 && this.IsInvincible))
  923. {
  924. return 0;
  925. }
  926. if (attacker != null)
  927. {
  928. if (hp < 0 && !IngoreHealEffect)
  929. {
  930. int healedEffect = this.Virtual.GetHealedEffect();
  931. int healEffect = (attacker.Virtual.GetUnitPro() == XmdsUnitPro.Priest) ? attacker.Virtual.GetHealEffect() : 0;
  932. if (healedEffect != 0 || healEffect != 0)
  933. {
  934. hp = CUtils.CastInt(hp * (1 + healEffect * 0.0001) * (1 + healedEffect * 0.0001));
  935. }
  936. }
  937. this.Statistic.LogDamage(attacker.Statistic, hp);
  938. }
  939. //传递加血事件
  940. if(hp < 0 && attacker != null)
  941. {
  942. int finalHP = hp;
  943. attacker.Virtual.DispatchAddOtherHPEvent(-hp, this, out finalHP);
  944. hp = -finalHP;
  945. }
  946. this.DoAddHP(-hp);
  947. if (attacker != null && sendHit)
  948. {
  949. if (hitMessage == null)
  950. {
  951. hitMessage = new UnitHitEvent();
  952. }
  953. hitMessage.object_id = this.ID;
  954. hitMessage.senderId = attacker == null ? 0 : attacker.ID;
  955. hitMessage.senderMasterId = attacker == null ? 0 : attacker.Virtual.GetMasterID();
  956. hitMessage.hp = hp;
  957. hitMessage.isSpecialHit = dmgSrc != DamageSource.Def;
  958. hitMessage.dmgSrc = dmgSrc;
  959. hitMessage.isDead = IsDead();
  960. queueEvent(hitMessage);
  961. }
  962. //if (IsDead())
  963. //{
  964. // changeState(new StateDead(this, attacker, false));
  965. // Parent.cb_unitDeadCallBack(this, attacker);
  966. // queueEvent(new UnitDeadEvent(ID, attacker == null ? 0 : attacker.ID, false, mInfo.RebirthTimeMS));
  967. //}
  968. return hp;
  969. }
  970. public void AddMP(int mp, InstanceUnit sender, bool sendMsg = true, bool force = false, AttackSource source = null)
  971. {
  972. if(mp == 0 || this.MaxMP <= 0)
  973. {
  974. return;
  975. }
  976. //传递扣定力事件
  977. if (mp < 0 && sender != null)
  978. {
  979. int finalHP = mp;
  980. sender.Virtual.DispatchAddMPEvent(mp, this, out finalHP, source);
  981. mp = finalHP;
  982. }
  983. this.DoAddMP(mp, force);
  984. }
  985. public void removeFromParent()
  986. {
  987. Parent.RemoveObjectByID(ID);
  988. }
  989. public void kill(InstanceUnit killer = null, bool sendHit = true, UnitHitEvent hitMessage = null)
  990. {
  991. ReduceHP(this.CurrentHP, killer, sendHit, hitMessage, true);
  992. }
  993. virtual protected void onResetAI()
  994. {
  995. this.doSomething();
  996. }
  997. public void resetAI()
  998. {
  999. next_state_queue.Clear();
  1000. onResetAI();
  1001. }
  1002. public override void faceTo(float d)
  1003. {
  1004. if (Info.IsTurnable) { base.faceTo(d); }
  1005. }
  1006. public override void faceTo(float x, float y)
  1007. {
  1008. if (Info.IsTurnable) { base.faceTo(x, y); }
  1009. }
  1010. /// <summary>
  1011. /// 瞬移
  1012. /// </summary>
  1013. /// <param name="x"></param>
  1014. /// <param name="y"></param>
  1015. public void transport(float x, float y, bool setDirction = false, float direction = 0)
  1016. {
  1017. this.SetActionStatus(UnitActionStatus.Transport);
  1018. this.changeState(new StateTransport(this), true);
  1019. setPos(x, y);
  1020. if (setDirction)
  1021. {
  1022. this.faceTo(direction);
  1023. }
  1024. SendForceSync();
  1025. if (mOnRegionTransport != null)
  1026. {
  1027. mOnRegionTransport.Invoke();
  1028. }
  1029. }
  1030. //-----------------------------------------------------------------------------------------------------//
  1031. public virtual void doSomething()
  1032. {
  1033. startIdle();
  1034. }
  1035. /// <summary>
  1036. /// 单位待机
  1037. /// </summary>
  1038. public bool startIdle(bool force = false)
  1039. {
  1040. if (current_state is StateIdle)
  1041. {
  1042. }
  1043. else
  1044. {
  1045. return changeState(new StateIdle(this), force);
  1046. }
  1047. return false;
  1048. }
  1049. /// <summary>
  1050. /// 直接复活
  1051. /// </summary>
  1052. public bool startRebirth(int max_hp = 0, int max_mp = 0)
  1053. {
  1054. if (IsDead())
  1055. {
  1056. this.DeadHide = false;
  1057. return changeState(new StateRebirth(this, max_hp, max_mp));
  1058. }
  1059. return false;
  1060. }
  1061. /// <summary>
  1062. /// 单位移动
  1063. /// </summary>
  1064. /// <param name="x"></param>
  1065. /// <param name="y"></param>
  1066. public bool startMoveTo(float x, float y)
  1067. {
  1068. return changeState(new StateMove(this, x, y));
  1069. }
  1070. /// <summary>
  1071. /// 调整射击位置
  1072. /// </summary>
  1073. /// <param name="expect_skill"></param>
  1074. /// <param name="target"></param>
  1075. /// <param name="onEndAction"></param>
  1076. public bool startAdjustLaunchSkill(SkillTemplate expect_skill, InstanceUnit target, Predicate<StateMove> onEndAction)
  1077. {
  1078. if (expect_skill.AttackKeepRange > 0 && expect_skill.AttackRange > expect_skill.AttackKeepRange)
  1079. {
  1080. float keep_range = GetSkillAttackRange(expect_skill.AttackKeepRange) + target.BodyBlockSize;
  1081. float distance = MathVector.getDistance(this.X, this.Y, target.X, target.Y);
  1082. if (distance < keep_range)
  1083. {
  1084. var half = (expect_skill.AttackRange - expect_skill.AttackKeepRange) / 2;
  1085. var md = (keep_range - distance) + (float)(RandomN.NextDouble() * half);
  1086. var target_pos = new Vector2(this.X, this.Y);
  1087. var rd = (CMath.PI_DIV_2 / 4);
  1088. var target_direction = this.Direction + CMath.PI_F - (rd / 2 + (float)(RandomN.NextDouble() * rd));
  1089. MathVector.movePolar(target_pos, target_direction, md);
  1090. if (!Parent.TryTouchMap(this, target_pos.X, target_pos.Y))
  1091. {
  1092. var back_pos = new Vector2(this.X, this.Y);
  1093. MathVector.movePolar(back_pos, target_direction, this.BodyBlockSize);
  1094. if (!Parent.TryTouchMap(this, back_pos.X, back_pos.Y))
  1095. {
  1096. var move = new StateMove(this, target_pos.X, target_pos.Y);
  1097. move.MinStepCheckCount = 0;
  1098. move.StopOnTouchMap = true;
  1099. move.EndMoveAction = onEndAction;
  1100. return this.changeState(move);
  1101. }
  1102. }
  1103. }
  1104. }
  1105. return false;
  1106. }
  1107. /// <summary>
  1108. /// 单位移动
  1109. /// </summary>
  1110. /// <param name="obj"></param>
  1111. public bool startFollowTo(InstanceZoneObject obj)
  1112. {
  1113. return changeState(new StateFollowObject(this, obj));
  1114. }
  1115. /// <summary>
  1116. /// 单位逃跑
  1117. /// </summary>
  1118. /// <param name="timeMS"></param>
  1119. /// <param name="distance"></param>
  1120. public bool startEscape(int timeMS, float distance = 0)
  1121. {
  1122. return changeState(new StateEscape(this, timeMS, distance));
  1123. }
  1124. /// <summary>
  1125. /// 和自身交互(搓炉石)
  1126. /// </summary>
  1127. /// <param name="timeMS"></param>
  1128. /// <param name="done"></param>
  1129. /// <param name="status"></param>
  1130. public StatePickObject startPickProgressSelf(int timeMS, StatePickObject.OnPickDone done, string status = null)
  1131. {
  1132. StatePickObject picking = new StatePickObject(this, this, timeMS, status, done);
  1133. changeState(picking);
  1134. return picking;
  1135. }
  1136. /// <summary>
  1137. /// 和目标交互
  1138. /// </summary>
  1139. /// <param name="item"></param>
  1140. /// <param name="timeMS"></param>
  1141. /// <param name="done"></param>
  1142. /// <param name="status"></param>
  1143. /// <returns></returns>
  1144. public StatePickObject startPickProgressObject(InstanceZoneObject item, int timeMS, StatePickObject.OnPickDone done, string status = null)
  1145. {
  1146. StatePickObject picking = new StatePickObject(this, item, timeMS, status, done);
  1147. changeState(picking);
  1148. return picking;
  1149. }
  1150. //-----------------------------------------------------------------------------------------------------------------
  1151. #region _SKILL_
  1152. //-----------------------------------------------------------------------------------------------------------------
  1153. public float GetSkillAttackRange(SkillTemplate skill)
  1154. {
  1155. return mIsAttackRangeIncludeBodySize ? BodyBlockSize + skill.AttackRange : skill.AttackRange;
  1156. }
  1157. public float GetSkillAttackRange(float range)
  1158. {
  1159. return (mIsAttackRangeIncludeBodySize ? BodyBlockSize + range : range);
  1160. }
  1161. /// <summary>
  1162. /// 判断当前目标在攻击范围内
  1163. /// </summary>
  1164. /// <param name="skill"></param>
  1165. /// <param name="unit"></param>
  1166. /// <returns></returns>
  1167. public bool IsTargetInSkillRange(SkillTemplate skill, InstanceUnit unit)
  1168. {
  1169. float rg = GetSkillAttackRange(skill);
  1170. float dr = skill.AttackAngle / 2;
  1171. if (Collider.Object_HitBody_TouchFan(unit, X, Y, rg, Direction - dr, Direction + dr))
  1172. {
  1173. return true;
  1174. }
  1175. return false;
  1176. }
  1177. [Obsolete]
  1178. public List<InstanceUnit> getSkillAttackableTargets(SkillTemplate skill, AttackReason reason)
  1179. {
  1180. float rg = GetSkillAttackRange(skill);
  1181. List<InstanceUnit> list = Parent.getObjectsRoundRange<InstanceUnit>(Collider.Object_HitBody_TouchRound, X, Y, rg , this.AoiStatus);
  1182. Parent.getAttackableUnits(this, list, skill.ExpectTarget, reason, skill);
  1183. return list;
  1184. }
  1185. public void getSkillAttackableTargets(SkillTemplate skill, List<InstanceUnit> list, AttackReason reason)
  1186. {
  1187. float rg = GetSkillAttackRange(skill);
  1188. Parent.getObjectsRoundRange<InstanceUnit>(Collider.Object_HitBody_TouchRound, X, Y, rg, list, this.AoiStatus);
  1189. Parent.getAttackableUnits(this, list, skill.ExpectTarget, reason, skill);
  1190. }
  1191. /// <summary>
  1192. /// 获得可用的技能
  1193. /// </summary>
  1194. /// <param name="expect"></param>
  1195. /// <returns></returns>
  1196. public SkillState getAvailableSkill(SkillTemplate.CastTarget expect)
  1197. {
  1198. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1199. {
  1200. SkillTemplate st = mAllSkills[si];
  1201. if (st.ExpectTarget == expect)
  1202. {
  1203. SkillState sst = mSkillStatus.Get(st.GetID());
  1204. if (sst.IsActive && sst.IsDone)
  1205. {
  1206. return sst;
  1207. }
  1208. }
  1209. }
  1210. return null;
  1211. }
  1212. /** 获取当前可自动释放的技能 */
  1213. public SkillState getAvailableAutoLaunchSkill(SkillTemplate.CastTarget expect)
  1214. {
  1215. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1216. {
  1217. SkillTemplate st = mAllSkills[si];
  1218. if (st.ExpectTarget == expect)
  1219. {
  1220. SkillState sst = mSkillStatus.Get(st.GetID());
  1221. if (sst.IsActive && sst.IsDone && sst.LaunchSkill.AutoLaunch && sst.CanAutoLaunch())
  1222. {
  1223. return sst;
  1224. }
  1225. }
  1226. }
  1227. return null;
  1228. }
  1229. /// <summary>
  1230. /// 获取当前最适合攻击的目标
  1231. /// </summary>
  1232. /// <param name="skill"></param>
  1233. /// <param name="reason"></param>
  1234. /// <param name="directionChange"></param>
  1235. /// <returns></returns>
  1236. public InstanceUnit getSkillAttackableFirstTarget(SkillTemplate skill, AttackReason reason, ref bool directionChange)
  1237. {
  1238. using (var list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  1239. {
  1240. getSkillAttackableTargets(skill, list, reason);
  1241. if (list.Count > 0)
  1242. {
  1243. float rg = GetSkillAttackRange(skill);
  1244. // 检测攻击范围内的单位 //
  1245. float dr = skill.AttackAngle / 2;
  1246. for (int i = 0; i < list.Count; i++)
  1247. {
  1248. InstanceUnit u = list[i];
  1249. if (Collider.Object_HitBody_TouchFan(u, X, Y, rg, Direction - dr, Direction + dr))
  1250. {
  1251. directionChange = false;
  1252. return u;
  1253. }
  1254. }
  1255. // 优先当前朝向的目标 //
  1256. dr = CMath.PI_DIV_2;
  1257. directionChange = true;
  1258. for (int i = 0; i < list.Count; i++)
  1259. {
  1260. InstanceUnit u = list[i];
  1261. if (Collider.Object_HitBody_TouchFan(u, X, Y, rg, Direction - dr, Direction + dr))
  1262. {
  1263. return u;
  1264. }
  1265. }
  1266. // 最后选取最近的目标 //
  1267. InstanceUnit min = null;
  1268. float min_len = float.MaxValue;
  1269. for (int i = 0; i < list.Count; i++)
  1270. {
  1271. InstanceUnit u = list[i];
  1272. float len = MathVector.getDistanceSquare(u.X, u.Y, X, Y);
  1273. if (min_len > len)
  1274. {
  1275. min_len = len;
  1276. min = u;
  1277. }
  1278. }
  1279. return min;
  1280. }
  1281. }
  1282. return null;
  1283. }
  1284. public struct LaunchSkillParam
  1285. {
  1286. public uint TargetUnitID;
  1287. public Vector2 SpellTargetPos;
  1288. public bool AutoFocusNearTarget;
  1289. public bool LaunchSetDirection; // 释放时是否重新设置方向
  1290. public float direction;
  1291. public bool IsAutoLaunch; // 是否自动战斗时释放
  1292. public bool IsInGuard; // 是否是自动战斗
  1293. public LaunchSkillParam(uint targetUnitID = 0, Vector2 target_pos = null, bool autoFocusNearTarget = false,
  1294. bool LaunchSetDirection = false, float direction = 0, bool IsAutoLaunch = false, bool IsInGuard = false)
  1295. {
  1296. this.TargetUnitID = targetUnitID;
  1297. this.SpellTargetPos = target_pos;
  1298. this.AutoFocusNearTarget = autoFocusNearTarget;
  1299. this.LaunchSetDirection = LaunchSetDirection;
  1300. this.direction = direction;
  1301. this.IsAutoLaunch = IsAutoLaunch;
  1302. this.IsInGuard = IsInGuard;
  1303. }
  1304. }
  1305. public StateSkill launchSkill(SkillState ss, LaunchSkillParam param)
  1306. {
  1307. if (ss == null) return null;
  1308. StateSkill current = CurrentState as StateSkill;
  1309. if (current != null && current.SkillData.IsManuallyCancelable)
  1310. {
  1311. //如果当前技能为手动取消//
  1312. if (current.Skill.ID == ss.ID)
  1313. {
  1314. //判断停止当前技能//
  1315. if (current.IsCancelableBySkill)
  1316. {
  1317. current.block();
  1318. }
  1319. }
  1320. //手动取消技能禁止其他技能打断//
  1321. return null;
  1322. }
  1323. if (mFormula.TryLaunchSkill(this, ss, ref param) && ss.TryLaunch())
  1324. {
  1325. if(param.IsAutoLaunch && !ss.CanAutoLaunch())
  1326. {
  1327. return null;
  1328. }
  1329. //沉默不能释放其他技能//
  1330. if (IsSilent && ss != mDefaultSkill)
  1331. {
  1332. return null;
  1333. }
  1334. // 自动战斗下,释放技能要在范围内
  1335. InstanceUnit target = null;
  1336. if (ss.Data.AttackMustBeInRange)
  1337. {
  1338. target = Parent.getUnit(param.TargetUnitID);
  1339. if (!ss.checkTargetRange(target))
  1340. {
  1341. return null;
  1342. }
  1343. }
  1344. //是否在合理的攻击范围内
  1345. if(param.IsInGuard && !ss.checkTargetInAttackRange(target, param))
  1346. {
  1347. return null;
  1348. }
  1349. if (ss.GetSkillType() == XmdsSkillType.petGiveAcitve)
  1350. {
  1351. mFormula.TriggerPetSkill(this, ss, ref param);
  1352. return null;
  1353. }
  1354. StateSkill state = new StateSkill(this, ss, param, ss.ActionSpeed, (st) =>
  1355. {
  1356. overLaunchSkill(ss, st);
  1357. if (mOnLaunchSkill != null)
  1358. {
  1359. mOnLaunchSkill.Invoke(this, ss);
  1360. }
  1361. });
  1362. if (state.tryLaunch())
  1363. {
  1364. this.Virtual.SetCombatState(BattleStatus.ReadyBattle);
  1365. Parent.cb_unitLaunchSkill(this, ss);
  1366. if (changeState(state))
  1367. {
  1368. //释放成功
  1369. if (param.LaunchSetDirection)
  1370. {
  1371. //Console.WriteLine("launchSkill - 设置方向: " + param.direction + ", " + this.ID);
  1372. //this.faceTo(param.direction);
  1373. //this.SendForceSync();
  1374. }
  1375. return state;
  1376. }
  1377. }
  1378. }
  1379. return null;
  1380. }
  1381. protected virtual void overLaunchSkill(SkillState ss, StateSkill state)
  1382. {
  1383. this.AddHP(-ss.Data.CostHP, null);
  1384. this.AddMP(-ss.Data.CostMP, null);
  1385. }
  1386. /// <summary>
  1387. /// 单位释放技能
  1388. /// </summary>
  1389. public StateSkill launchSkill(int skillID, LaunchSkillParam param)
  1390. {
  1391. SkillState skill = getSkillState(skillID);
  1392. return launchSkill(skill, param);
  1393. }
  1394. /// <summary>
  1395. /// 释放随机技能,一般用于AI
  1396. /// </summary>
  1397. /// <param name="expectTarget"></param>
  1398. /// <param name="param"></param>
  1399. /// <returns></returns>
  1400. public virtual StateSkill launchRandomSkill(SkillTemplate.CastTarget expectTarget, LaunchSkillParam param)
  1401. {
  1402. StateSkill current = CurrentState as StateSkill;
  1403. if (current != null && !current.IsCancelableBySkill)
  1404. {
  1405. return null;
  1406. }
  1407. int rand = RandomN.Next(0, mAllSkills.Count);
  1408. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1409. {
  1410. SkillTemplate st = mAllSkills[CMath.cycNum(rand, si, mAllSkills.Count)];
  1411. if (st.ExpectTarget == expectTarget)
  1412. {
  1413. SkillState sst = mSkillStatus.Get(st.GetID());
  1414. if (sst.LaunchSkill.AutoLaunch && sst.TryLaunch())
  1415. {
  1416. StateSkill state = launchSkill(sst, param);
  1417. if (state != null)
  1418. {
  1419. return state;
  1420. }
  1421. }
  1422. }
  1423. }
  1424. return null;
  1425. }
  1426. public virtual StateSkill launchRandomSkillForAll(LaunchSkillParam param)
  1427. {
  1428. StateSkill current = CurrentState as StateSkill;
  1429. if (current != null && !current.IsCancelableBySkill)
  1430. {
  1431. return null;
  1432. }
  1433. int rand = RandomN.Next(0, mAllSkills.Count);
  1434. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1435. {
  1436. SkillTemplate st = mAllSkills[CMath.cycNum(rand, si, mAllSkills.Count)];
  1437. SkillState sst = mSkillStatus.Get(st.GetID());
  1438. if (sst.LaunchSkill.AutoLaunch && sst.TryLaunch())
  1439. {
  1440. StateSkill state = launchSkill(sst, param);
  1441. if (state != null)
  1442. {
  1443. return state;
  1444. }
  1445. }
  1446. }
  1447. return null;
  1448. }
  1449. /// <summary>
  1450. /// 尝试取消当前技能,打出连击
  1451. /// </summary>
  1452. /// <param name="target"></param>
  1453. /// <param name="autoFocusNearTarget"></param>
  1454. /// <returns></returns>
  1455. public virtual bool tryLaunchRandomSkillAndCancelCurrentSkill(InstanceUnit target, bool autoFocusNearTarget = false)
  1456. {
  1457. StateSkill current = CurrentState as StateSkill;
  1458. if (current != null && !current.IsChanting && current.IsCancelableBySkill)
  1459. {
  1460. LaunchSkillParam param = new LaunchSkillParam(target.ID, null, autoFocusNearTarget);
  1461. //优先多段攻击//
  1462. if (current.SkillData.IsSingleAction)
  1463. {
  1464. if (IsTargetInSkillRange(current.SkillData, target))
  1465. {
  1466. StateSkill st = launchSkill(current.SkillData.ID, param);
  1467. if (st != null)
  1468. {
  1469. return true;
  1470. }
  1471. }
  1472. }
  1473. //随机其他技能//
  1474. int rand = RandomN.Next(0, mAllSkills.Count);
  1475. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1476. {
  1477. SkillTemplate st = mAllSkills[CMath.cycNum(rand, si, mAllSkills.Count)];
  1478. if (Parent.IsAttackable(this, target, st.ExpectTarget, AttackReason.Attack, st))
  1479. {
  1480. SkillState sst = mSkillStatus.Get(st.GetID());
  1481. if (sst.LaunchSkill.AutoLaunch && IsTargetInSkillRange(st, target))
  1482. {
  1483. StateSkill state = launchSkill(sst, param);
  1484. if (state != null)
  1485. {
  1486. return true;
  1487. }
  1488. }
  1489. }
  1490. }
  1491. }
  1492. return false;
  1493. }
  1494. /// <summary>
  1495. /// 尝试在范围内找到目标释放技能,并进入StateFollowAndAttack,自己走过去打。
  1496. /// </summary>
  1497. /// <param name="range"></param>
  1498. /// <param name="skill_auto_launchable"></param>
  1499. /// <returns></returns>
  1500. public virtual bool tryFollowAndLaunchRandomSkillToTargetInRange(float range, bool skill_auto_launchable = false)
  1501. {
  1502. if (!IsNoneSkill)
  1503. {
  1504. SkillState[] skills = mSkillStatus.SkillsArray;
  1505. CUtils.RandomArray(RandomN, skills);
  1506. using (var list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  1507. {
  1508. //随机找个目标施法//
  1509. Parent.getObjectsRoundRange<InstanceUnit>(Collider.Object_Pos_IncludeInRound, X, Y, Info.GuardRange, list , this.AoiStatus);
  1510. DoAndRemoveCollection.UpdateAndRemove<InstanceUnit>(list, (InstanceUnit u) =>
  1511. {
  1512. return !u.IsActive;
  1513. });
  1514. if (list.Count == 0) { return false; }
  1515. CUtils.RandomList(Parent.RandomN, list);
  1516. foreach (SkillState skill in skills)
  1517. {
  1518. if ((!skill_auto_launchable || skill.LaunchSkill.AutoLaunch) && skill.TryLaunch())
  1519. {
  1520. for (int i = 0; i < list.Count; i++)
  1521. {
  1522. InstanceUnit u = list[i];
  1523. if (Parent.IsAttackable(this, u, skill.Data.ExpectTarget, AttackReason.Attack, skill.Data))
  1524. {
  1525. //检测是否有可释放技能//
  1526. changeState(new StateFollowAndAttack(this, u, skill.Data.ExpectTarget));
  1527. return true;
  1528. }
  1529. }
  1530. }
  1531. }
  1532. }
  1533. }
  1534. return false;
  1535. }
  1536. #endregion
  1537. //-----------------------------------------------------------------------------------------------------------------
  1538. internal void deadDropItems(int force)
  1539. {
  1540. foreach (KeyValuePair<ItemTemplate, DropItem> e in mDropItems.Drop(Parent, Parent.RandomN))
  1541. {
  1542. float x;
  1543. float y;
  1544. CMath.RandomPosInRound(RandomN, X, Y, e.Value.DropPosRange, out x, out y);
  1545. Parent.AddItem(e.Key, e.Key.Name, x, y, CMath.RandomAngle(RandomN), force, e.Key.Name, this);
  1546. }
  1547. }
  1548. protected bool tryPickObject(InstanceUnit unit)
  1549. {
  1550. if (!Parent.IsVisibleAOI(this, unit))
  1551. {
  1552. return false;
  1553. }
  1554. bool ret = true;
  1555. if (mOnTryPickUnit != null)
  1556. {
  1557. foreach (TryPickUnitHandler trypick in mOnTryPickUnit.GetInvocationList())
  1558. {
  1559. if (!trypick.Invoke(this, unit))
  1560. {
  1561. ret = false;
  1562. }
  1563. }
  1564. }
  1565. return ret;
  1566. }
  1567. public void PickUnit(InstanceUnit pickable)
  1568. {
  1569. if (tryPickObject(pickable))
  1570. {
  1571. Parent.cb_unitPickUnitCallBack(this, pickable);
  1572. if (mOnPickUnit != null)
  1573. {
  1574. mOnPickUnit.Invoke(this, pickable);
  1575. }
  1576. }
  1577. }
  1578. public CommonAI.Data.SceneType GetSceneType()
  1579. {
  1580. return mZone.SceneType;
  1581. }
  1582. //-----------------------------------------------------------------------------------------------------//
  1583. #region Environment
  1584. //-----------------------------------------------------------------------------------------------------//
  1585. private HashMap<string, EnvironmentVar> EnvironmentVarMap = new HashMap<string, EnvironmentVar>();
  1586. public void SetEnvironmentVar(string key, object value, bool syncToClient = false)
  1587. {
  1588. if (!string.IsNullOrEmpty(key))
  1589. {
  1590. EnvironmentVar var = EnvironmentVarMap.Get(key);
  1591. if (var != null)
  1592. {
  1593. if (EnvironmentVar.ALWAYS_SYNC_ENVIRONMENT_VAR || (var.SyncToClient && var.Value != value))
  1594. {
  1595. queueEvent(new PlayerSyncEnvironmentVarEvent(ID, key, value));
  1596. }
  1597. var.Value = value;
  1598. }
  1599. else
  1600. {
  1601. var = new EnvironmentVar(key, syncToClient, value);
  1602. EnvironmentVarMap.Add(key, var);
  1603. if (EnvironmentVar.ALWAYS_SYNC_ENVIRONMENT_VAR || var.SyncToClient)
  1604. {
  1605. queueEvent(new PlayerSyncEnvironmentVarEvent(ID, key, value));
  1606. }
  1607. }
  1608. }
  1609. }
  1610. public T GetEnvironmentVarAs<T>(string key)
  1611. {
  1612. if (!string.IsNullOrEmpty(key))
  1613. {
  1614. EnvironmentVar var = EnvironmentVarMap.Get(key);
  1615. if (var != null)
  1616. {
  1617. try
  1618. {
  1619. return (T)var.Value;
  1620. }
  1621. catch (Exception err)
  1622. {
  1623. log.Warn("GetEnvironmentVarAs : " + key + ", catch: " + err);
  1624. }
  1625. }
  1626. }
  1627. return default(T);
  1628. }
  1629. public int ListEnvironmentVars(List<EnvironmentVar> list)
  1630. {
  1631. list.AddRange(EnvironmentVarMap.Values);
  1632. return EnvironmentVarMap.Count;
  1633. }
  1634. public List<EnvironmentVar> ListEnvironmentVars()
  1635. {
  1636. return new List<EnvironmentVar>(EnvironmentVarMap.Values);
  1637. }
  1638. public ClientStruct.ZoneEnvironmentVar[] GetCurrentUnitVars()
  1639. {
  1640. ClientStruct.ZoneEnvironmentVar[] ret = new ClientStruct.ZoneEnvironmentVar[EnvironmentVarMap.Count];
  1641. int i = 0;
  1642. try
  1643. {
  1644. foreach (EnvironmentVar var in EnvironmentVarMap.Values)
  1645. {
  1646. ret[i].Key = var.Key;
  1647. ret[i].Value = var.Value;
  1648. ret[i].SyncToClient = var.SyncToClient;
  1649. i++;
  1650. }
  1651. }
  1652. catch(Exception e)
  1653. {
  1654. log.Warn("GetCurrentUnitVars catch: " + ret.Length + ", " + EnvironmentVarMap.Count + ", " + i + ", e: " + e);
  1655. }
  1656. return ret;
  1657. }
  1658. #endregion
  1659. //-----------------------------------------------------------------------------------------------------//
  1660. //-----------------------------------------------------------------------------------------------------//
  1661. #region SceneEvents
  1662. //-----------------------------------------------------------------------------------------------------//
  1663. private HashMap<int, UnitEventTriggerCollection> mBindEvents = new HashMap<int, UnitEventTriggerCollection>();
  1664. public void BindUnitEvent(int unit_event_id)
  1665. {
  1666. if (!mBindEvents.ContainsKey(unit_event_id))
  1667. {
  1668. UnitEventTemplate uet = Templates.getUnitEvent(unit_event_id);
  1669. if (uet != null)
  1670. {
  1671. uet = uet.Clone() as UnitEventTemplate;
  1672. UnitEventTriggerCollection bind_event = new UnitEventTriggerCollection(this);
  1673. bind_event.Bind(uet.Events);
  1674. mBindEvents.Add(unit_event_id, bind_event);
  1675. }
  1676. }
  1677. }
  1678. protected virtual void clearBindEvents()
  1679. {
  1680. foreach (var evt in mBindEvents.Values)
  1681. {
  1682. evt.Dispose();
  1683. }
  1684. mBindEvents.Clear();
  1685. }
  1686. #endregion
  1687. //-----------------------------------------------------------------------------------------------------//
  1688. //-----------------------------------------------------------------------------------------------------//
  1689. }
  1690. }