InstanceUnit.cs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  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.hitMasterId = this.Virtual.GetMasterID();
  680. evt.hp = reduceHP;
  681. evt.isDead = IsDead();
  682. evt.isCritical = source.Attack.MaskMustCritical;
  683. evt.effect = source.OutHitEffect;
  684. evt.SourceAttack = source.Attack;
  685. evt.client_state = source.OutClientState;
  686. if(source != null && attacker != null && source.FromSkillType == XmdsSkillType.cardSkill && this.IsMonster && attacker.IsMonster)
  687. {
  688. evt.InViewForceSend = true;
  689. }
  690. queueEvent(evt);
  691. }
  692. if (reduceHP > 0)
  693. {
  694. source.HasHitted = true;
  695. onDamaged(attacker, source, reduceHP);
  696. Parent.cb_unitDamageCallBack(this, attacker, reduceHP, source);
  697. if (IsDead())
  698. {
  699. doDeadProcess(attacker, source);
  700. return;
  701. }
  702. }
  703. // 非免控,才会有受击
  704. if (!this.IsIgnoreControl && source.OutIsDamage && Moveable)
  705. {
  706. changeState(new StateDamage(this, source, attacker));
  707. }
  708. doHitAttackEndEffect(attacker, source);
  709. return;
  710. }
  711. }
  712. /** 执行死亡处理逻辑 */
  713. private void doDeadProcess(InstanceUnit attacker, AttackSource source)
  714. {
  715. if (this.IsMonster)
  716. {
  717. if (this.mProcessDeadCallbackTime + 1000 > CommonLang.CUtils.localTimeMS)
  718. {
  719. log.Info("cb_unitDeadCallBack 跳过:" + this.mProcessDeadCallbackTime + ", " + this.Info.ID + ", " + this.ID);
  720. return;
  721. }
  722. if(this.Virtual.GetMaType() >= 4 && this.Level > 80)
  723. {
  724. log.Info("boss死亡:" + this.mProcessDeadCallbackTime + ", 单位id=" + this.Info.ID + ", 场景Id=" +
  725. this.Parent.GetSceneID() + ", " + this.mZone.UUID + ", " + (attacker == null ? "null" : attacker.PlayerUUID));
  726. }
  727. }
  728. mDeadTime = Parent.PassTimeMS;
  729. onDead(attacker);
  730. Parent.cb_unitDeadCallBack(this, attacker);
  731. queueEvent(new UnitDeadEvent(ID, attacker.ID, source.OutIsCrush, mInfo.RebirthTimeMS));
  732. // 被击碎,秒杀 //
  733. if (source.OutIsCrush)
  734. {
  735. Parent.queueEvent(new AddEffectEvent(this.ID, X, Y, Direction, source.Attack.CrushEffect));
  736. changeState(new StateDead(this, attacker, true));
  737. }
  738. else
  739. {
  740. if (!Moveable)
  741. {
  742. changeState(new StateDead(this, attacker));
  743. }
  744. else if (source.OutHasKnockDown || source.OutHasFly)
  745. {
  746. if (!changeState(new StateDamage(this, source, attacker)))
  747. {
  748. changeState(new StateDead(this, attacker));
  749. }
  750. }
  751. else
  752. {
  753. changeState(new StateDead(this, attacker));
  754. }
  755. }
  756. doHitAttackEndEffect(attacker, source);
  757. }
  758. /// <summary>
  759. /// 死亡后自爆或者触发法术
  760. /// </summary>
  761. /// <param name="attacker"></param>
  762. /// <param name="source"></param>
  763. private void doHitAttackEndEffect(InstanceUnit attacker, AttackSource source)
  764. {
  765. if (source.Attack.Buff != null)
  766. {
  767. AddBuff(source.Attack.Buff, attacker);
  768. }
  769. if (source.Attack.Spell != null)
  770. {
  771. Parent.attackLaunchSpell(source.FromSkillType, attacker, this, source);
  772. }
  773. }
  774. // 单位获取道具
  775. protected virtual bool tryGotItem(InstanceItem item, out bool removeItem)
  776. {
  777. if (!Parent.IsVisibleAOI(this, item))
  778. {
  779. removeItem = false;
  780. return false;
  781. }
  782. if (item.Info.DropMoneyMin > 0 && item.Info.DropMoneyMax > 0)
  783. {
  784. int min = Math.Min(item.Info.DropMoneyMin, item.Info.DropMoneyMax);
  785. int max = Math.Max(item.Info.DropMoneyMin, item.Info.DropMoneyMax);
  786. int money = RandomN.Next(min, max + 1);
  787. this.CurrentMoney += money;
  788. removeItem = item.Info.RemoveOnFinishPick;
  789. return true;
  790. }
  791. if (item.Info.GotOnUse)
  792. {
  793. // 获取后立即使用 //
  794. if (UseItem(item.Info, item.ItemCreater))
  795. {
  796. removeItem = item.Info.RemoveOnFinishPick;
  797. return true;
  798. }
  799. }
  800. else
  801. {
  802. // 获取后进背包 //
  803. if (AddItemToEmptyInventory(item.Info) > 0)
  804. {
  805. removeItem = item.Info.RemoveOnFinishPick;
  806. return true;
  807. }
  808. }
  809. removeItem = false;
  810. return false;
  811. }
  812. internal bool doGotInstanceItem(InstanceItem item, out bool removeItem, out int pickTimes)
  813. {
  814. pickTimes = 0;
  815. var ret = tryGotItem(item, out removeItem);
  816. if (ret)
  817. {
  818. pickTimes = Parent.cb_unitGotInstanceItemCallBack(this, item);
  819. if (item.Info.GotEffect != null)
  820. {
  821. queueEvent(new UnitEffectEvent(ID, item.Info.GotEffect));
  822. }
  823. }
  824. return ret;
  825. }
  826. internal void doGotInventoryItem(InventorySlot slot, ItemTemplate item, int index, int count)
  827. {
  828. mFormula.OnGotInventoryItem(this, item);
  829. queueEvent(new UnitSyncInventoryItemEvent(ID, item.ID, index, slot.Count));
  830. Parent.cb_unitGotInventoryItemCallBack(this, item, count);
  831. // 添加装备Buff //
  832. if (item.EquipBuffs != null)
  833. {
  834. foreach (LaunchBuff buff in item.EquipBuffs)
  835. {
  836. AddBuff(buff, this, true);
  837. }
  838. }
  839. }
  840. internal void doLostInventoryItem(InventorySlot slot, ItemTemplate item, int index, int count)
  841. {
  842. mFormula.OnLostInventoryItem(this, item);
  843. queueEvent(new UnitSyncInventoryItemEvent(ID, item.ID, index, slot.Count));
  844. Parent.cb_unitLostInventoryItemCallBack(this, item, count);
  845. // 移除装备Buff //
  846. if (item.EquipBuffs != null)
  847. {
  848. foreach (LaunchBuff buff in item.EquipBuffs)
  849. {
  850. removeBuff(buff.BuffID);
  851. }
  852. }
  853. }
  854. // 单位获取道具
  855. internal void doGotBuff(InstanceUnit.BuffState buff)
  856. {
  857. Parent.cb_unitGotBuffCallBack(this, buff);
  858. }
  859. internal void doLostBuff(InstanceUnit.BuffState buff)
  860. {
  861. Parent.cb_unitLostBuffCallBack(this, buff);
  862. }
  863. public bool UseItem(int itemTemplateID, InstanceUnit item_creater = null)
  864. {
  865. ItemTemplate item = Templates.getItem(itemTemplateID);
  866. if (item != null)
  867. {
  868. return UseItem(item, item_creater);
  869. }
  870. return false;
  871. }
  872. public bool UseItem(ItemTemplate item, InstanceUnit item_creater = null)
  873. {
  874. if (item_creater == null)
  875. {
  876. item_creater = this;
  877. }
  878. if (tryUseItem(item, item_creater))
  879. {
  880. beginUseItem(item);
  881. // 如果关键帧绑定特效
  882. if (item.UseEffect != null)
  883. {
  884. queueEvent(new UnitEffectEvent(ID, item.UseEffect));
  885. }
  886. // 如果关键帧绑定释放法术
  887. if (item.UseSpell != null)
  888. {
  889. Parent.unitLaunchSpell(XmdsSkillType.none, item_creater, item.UseSpell, X, Y);
  890. }
  891. if (item.UseSummon != null)
  892. {
  893. Parent.unitSummonUnit(item_creater, item.UseSummon);
  894. }
  895. // 如果关键帧绑定自己释放BUFF
  896. if (item.UseBuffs != null)
  897. {
  898. foreach (LaunchBuff buff in item.UseBuffs)
  899. {
  900. this.AddBuff(buff, item_creater);
  901. }
  902. }
  903. mFormula.OnUseItem(this, item, item_creater);
  904. queueEvent(new UnitUseItemEvent(ID, item.ID));
  905. Parent.cb_unitUseItemCallBack(this, item, item_creater);
  906. Statistic.LogUseItem(item);
  907. return true;
  908. }
  909. return false;
  910. }
  911. //-----------------------------------------------------------------------------------------------------//
  912. /// <summary>
  913. /// 有伤害源的扣血
  914. /// </summary>
  915. /// <param name="hp"></param>
  916. /// <param name="attacker"></param>
  917. /// <param name="sendHit"></param>
  918. /// <param name="hitMessage"></param>
  919. public int ReduceHP(int hp, InstanceUnit attacker, bool sendHit = true, UnitHitEvent hitMessage = null,
  920. bool IngoreHealEffect = false, DamageSource dmgSrc = DamageSource.Def)
  921. {
  922. //1.目标无敌,不扣血
  923. if (IsDead() || hp == 0 || ( hp > 0 && this.IsInvincible))
  924. {
  925. return 0;
  926. }
  927. if (attacker != null)
  928. {
  929. if (hp < 0 && !IngoreHealEffect)
  930. {
  931. int healedEffect = this.Virtual.GetHealedEffect();
  932. int healEffect = (attacker.Virtual.GetUnitPro() == XmdsUnitPro.Priest) ? attacker.Virtual.GetHealEffect() : 0;
  933. if (healedEffect != 0 || healEffect != 0)
  934. {
  935. hp = CUtils.CastInt(hp * (1 + healEffect * 0.0001) * (1 + healedEffect * 0.0001));
  936. }
  937. }
  938. this.Statistic.LogDamage(attacker.Statistic, hp);
  939. }
  940. //2. 针对有发送者的伤害来源
  941. if(attacker != null)
  942. {
  943. if (hp < 0)
  944. {
  945. //2.1 传递加血事件
  946. int finalHP = hp;
  947. attacker.Virtual.DispatchAddOtherHPEvent(-hp, this, out finalHP);
  948. hp = -finalHP;
  949. //2.2 道灵对宠物加血,需要有个系数
  950. if(attacker.IsPlayer && this.IsPet && attacker.Virtual.GetUnitPro() == XmdsUnitPro.Priest)
  951. {
  952. hp = (int)(hp * XmdsConstConfig.PET_HEALD_RATIO);
  953. }
  954. }
  955. else if(this.IsPlayer)
  956. {
  957. //2.2 如果为玩家,伤害来源存在且为怪物,宠物可以分担伤害
  958. InstanceUnit petUnit = this.Virtual.GetPetUnit();
  959. if(petUnit != null)
  960. {
  961. int petShareDmg = Math.Max(1, (int)(hp * XmdsConstConfig.PET_SHARE_MASTERDMG_RATIO));
  962. hp = Math.Max(1, hp - petShareDmg);
  963. petUnit.AddHP(-petShareDmg, this);
  964. }
  965. }
  966. }
  967. this.DoAddHP(-hp);
  968. if (attacker != null && sendHit)
  969. {
  970. if (hitMessage == null)
  971. {
  972. hitMessage = new UnitHitEvent();
  973. }
  974. hitMessage.object_id = this.ID;
  975. hitMessage.senderId = attacker == null ? 0 : attacker.ID;
  976. hitMessage.senderMasterId = attacker == null ? 0 : attacker.Virtual.GetMasterID();
  977. hitMessage.hitMasterId = this.Virtual.GetMasterID();
  978. hitMessage.hp = hp;
  979. hitMessage.isSpecialHit = dmgSrc != DamageSource.Def;
  980. hitMessage.dmgSrc = dmgSrc;
  981. hitMessage.isDead = IsDead();
  982. queueEvent(hitMessage);
  983. }
  984. //if (IsDead())
  985. //{
  986. // changeState(new StateDead(this, attacker, false));
  987. // Parent.cb_unitDeadCallBack(this, attacker);
  988. // queueEvent(new UnitDeadEvent(ID, attacker == null ? 0 : attacker.ID, false, mInfo.RebirthTimeMS));
  989. //}
  990. return hp;
  991. }
  992. public void AddMP(int mp, InstanceUnit sender, bool sendMsg = true, bool force = false, AttackSource source = null)
  993. {
  994. if(mp == 0 || this.MaxMP <= 0)
  995. {
  996. return;
  997. }
  998. //传递扣定力事件
  999. if (mp < 0 && sender != null)
  1000. {
  1001. int finalHP = mp;
  1002. sender.Virtual.DispatchAddMPEvent(mp, this, out finalHP, source);
  1003. mp = finalHP;
  1004. }
  1005. this.DoAddMP(mp, force);
  1006. }
  1007. public void removeFromParent()
  1008. {
  1009. Parent.RemoveObjectByID(ID);
  1010. }
  1011. public void kill(InstanceUnit killer = null, bool sendHit = true, UnitHitEvent hitMessage = null)
  1012. {
  1013. ReduceHP(this.CurrentHP, killer, sendHit, hitMessage, true);
  1014. }
  1015. virtual protected void onResetAI()
  1016. {
  1017. this.doSomething();
  1018. }
  1019. public void resetAI()
  1020. {
  1021. next_state_queue.Clear();
  1022. onResetAI();
  1023. }
  1024. public override void faceTo(float d)
  1025. {
  1026. if (Info.IsTurnable) { base.faceTo(d); }
  1027. }
  1028. public override void faceTo(float x, float y)
  1029. {
  1030. if (Info.IsTurnable) { base.faceTo(x, y); }
  1031. }
  1032. /// <summary>
  1033. /// 瞬移
  1034. /// </summary>
  1035. /// <param name="x"></param>
  1036. /// <param name="y"></param>
  1037. public void transport(float x, float y, bool setDirction = false, float direction = 0)
  1038. {
  1039. this.SetActionStatus(UnitActionStatus.Transport);
  1040. this.changeState(new StateTransport(this), true);
  1041. setPos(x, y);
  1042. if (setDirction)
  1043. {
  1044. this.faceTo(direction);
  1045. }
  1046. SendForceSync();
  1047. if (mOnRegionTransport != null)
  1048. {
  1049. mOnRegionTransport.Invoke();
  1050. }
  1051. }
  1052. //-----------------------------------------------------------------------------------------------------//
  1053. public virtual void doSomething()
  1054. {
  1055. startIdle();
  1056. }
  1057. /// <summary>
  1058. /// 单位待机
  1059. /// </summary>
  1060. public bool startIdle(bool force = false)
  1061. {
  1062. if (current_state is StateIdle)
  1063. {
  1064. }
  1065. else
  1066. {
  1067. return changeState(new StateIdle(this), force);
  1068. }
  1069. return false;
  1070. }
  1071. /// <summary>
  1072. /// 直接复活
  1073. /// </summary>
  1074. public bool startRebirth(int max_hp = 0, int max_mp = 0)
  1075. {
  1076. if (IsDead())
  1077. {
  1078. this.DeadHide = false;
  1079. return changeState(new StateRebirth(this, max_hp, max_mp));
  1080. }
  1081. return false;
  1082. }
  1083. /// <summary>
  1084. /// 单位移动
  1085. /// </summary>
  1086. /// <param name="x"></param>
  1087. /// <param name="y"></param>
  1088. public bool startMoveTo(float x, float y)
  1089. {
  1090. return changeState(new StateMove(this, x, y));
  1091. }
  1092. /// <summary>
  1093. /// 调整射击位置
  1094. /// </summary>
  1095. /// <param name="expect_skill"></param>
  1096. /// <param name="target"></param>
  1097. /// <param name="onEndAction"></param>
  1098. public bool startAdjustLaunchSkill(SkillTemplate expect_skill, InstanceUnit target, Predicate<StateMove> onEndAction)
  1099. {
  1100. if (expect_skill.AttackKeepRange > 0 && expect_skill.AttackRange > expect_skill.AttackKeepRange)
  1101. {
  1102. float keep_range = GetSkillAttackRange(expect_skill.AttackKeepRange) + target.BodyBlockSize;
  1103. float distance = MathVector.getDistance(this.X, this.Y, target.X, target.Y);
  1104. if (distance < keep_range)
  1105. {
  1106. var half = (expect_skill.AttackRange - expect_skill.AttackKeepRange) / 2;
  1107. var md = (keep_range - distance) + (float)(RandomN.NextDouble() * half);
  1108. var target_pos = new Vector2(this.X, this.Y);
  1109. var rd = (CMath.PI_DIV_2 / 4);
  1110. var target_direction = this.Direction + CMath.PI_F - (rd / 2 + (float)(RandomN.NextDouble() * rd));
  1111. MathVector.movePolar(target_pos, target_direction, md);
  1112. if (!Parent.TryTouchMap(this, target_pos.X, target_pos.Y))
  1113. {
  1114. var back_pos = new Vector2(this.X, this.Y);
  1115. MathVector.movePolar(back_pos, target_direction, this.BodyBlockSize);
  1116. if (!Parent.TryTouchMap(this, back_pos.X, back_pos.Y))
  1117. {
  1118. var move = new StateMove(this, target_pos.X, target_pos.Y);
  1119. move.MinStepCheckCount = 0;
  1120. move.StopOnTouchMap = true;
  1121. move.EndMoveAction = onEndAction;
  1122. return this.changeState(move);
  1123. }
  1124. }
  1125. }
  1126. }
  1127. return false;
  1128. }
  1129. /// <summary>
  1130. /// 单位移动
  1131. /// </summary>
  1132. /// <param name="obj"></param>
  1133. public bool startFollowTo(InstanceZoneObject obj)
  1134. {
  1135. return changeState(new StateFollowObject(this, obj));
  1136. }
  1137. /// <summary>
  1138. /// 单位逃跑
  1139. /// </summary>
  1140. /// <param name="timeMS"></param>
  1141. /// <param name="distance"></param>
  1142. public bool startEscape(int timeMS, float distance = 0)
  1143. {
  1144. return changeState(new StateEscape(this, timeMS, distance));
  1145. }
  1146. /// <summary>
  1147. /// 和自身交互(搓炉石)
  1148. /// </summary>
  1149. /// <param name="timeMS"></param>
  1150. /// <param name="done"></param>
  1151. /// <param name="status"></param>
  1152. public StatePickObject startPickProgressSelf(int timeMS, StatePickObject.OnPickDone done, string status = null)
  1153. {
  1154. StatePickObject picking = new StatePickObject(this, this, timeMS, status, done);
  1155. changeState(picking);
  1156. return picking;
  1157. }
  1158. /// <summary>
  1159. /// 和目标交互
  1160. /// </summary>
  1161. /// <param name="item"></param>
  1162. /// <param name="timeMS"></param>
  1163. /// <param name="done"></param>
  1164. /// <param name="status"></param>
  1165. /// <returns></returns>
  1166. public StatePickObject startPickProgressObject(InstanceZoneObject item, int timeMS, StatePickObject.OnPickDone done, string status = null)
  1167. {
  1168. StatePickObject picking = new StatePickObject(this, item, timeMS, status, done);
  1169. changeState(picking);
  1170. return picking;
  1171. }
  1172. //-----------------------------------------------------------------------------------------------------------------
  1173. #region _SKILL_
  1174. //-----------------------------------------------------------------------------------------------------------------
  1175. public float GetSkillAttackRange(SkillTemplate skill)
  1176. {
  1177. return mIsAttackRangeIncludeBodySize ? BodyBlockSize + skill.AttackRange : skill.AttackRange;
  1178. }
  1179. public float GetSkillAttackRange(float range)
  1180. {
  1181. return (mIsAttackRangeIncludeBodySize ? BodyBlockSize + range : range);
  1182. }
  1183. /// <summary>
  1184. /// 判断当前目标在攻击范围内
  1185. /// </summary>
  1186. /// <param name="skill"></param>
  1187. /// <param name="unit"></param>
  1188. /// <returns></returns>
  1189. public bool IsTargetInSkillRange(SkillTemplate skill, InstanceUnit unit)
  1190. {
  1191. float rg = GetSkillAttackRange(skill);
  1192. float dr = skill.AttackAngle / 2;
  1193. if (Collider.Object_HitBody_TouchFan(unit, X, Y, rg, Direction - dr, Direction + dr))
  1194. {
  1195. return true;
  1196. }
  1197. return false;
  1198. }
  1199. [Obsolete]
  1200. public List<InstanceUnit> getSkillAttackableTargets(SkillTemplate skill, AttackReason reason)
  1201. {
  1202. float rg = GetSkillAttackRange(skill);
  1203. List<InstanceUnit> list = Parent.getObjectsRoundRange<InstanceUnit>(Collider.Object_HitBody_TouchRound, X, Y, rg , this.AoiStatus);
  1204. Parent.getAttackableUnits(this, list, skill.ExpectTarget, reason, skill);
  1205. return list;
  1206. }
  1207. public void getSkillAttackableTargets(SkillTemplate skill, List<InstanceUnit> list, AttackReason reason)
  1208. {
  1209. float rg = GetSkillAttackRange(skill);
  1210. Parent.getObjectsRoundRange<InstanceUnit>(Collider.Object_HitBody_TouchRound, X, Y, rg, list, this.AoiStatus);
  1211. Parent.getAttackableUnits(this, list, skill.ExpectTarget, reason, skill);
  1212. }
  1213. /// <summary>
  1214. /// 获得可用的技能
  1215. /// </summary>
  1216. /// <param name="expect"></param>
  1217. /// <returns></returns>
  1218. public SkillState getAvailableSkill(SkillTemplate.CastTarget expect)
  1219. {
  1220. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1221. {
  1222. SkillTemplate st = mAllSkills[si];
  1223. if (st.ExpectTarget == expect)
  1224. {
  1225. SkillState sst = mSkillStatus.Get(st.GetID());
  1226. if (sst.IsActive && sst.IsDone)
  1227. {
  1228. return sst;
  1229. }
  1230. }
  1231. }
  1232. return null;
  1233. }
  1234. /** 获取当前可自动释放的技能 */
  1235. public SkillState getAvailableAutoLaunchSkill(SkillTemplate.CastTarget expect)
  1236. {
  1237. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1238. {
  1239. SkillTemplate st = mAllSkills[si];
  1240. if (st.ExpectTarget == expect)
  1241. {
  1242. SkillState sst = mSkillStatus.Get(st.GetID());
  1243. if (sst.IsActive && sst.IsDone && sst.LaunchSkill.AutoLaunch && sst.CanAutoLaunch())
  1244. {
  1245. return sst;
  1246. }
  1247. }
  1248. }
  1249. return null;
  1250. }
  1251. /// <summary>
  1252. /// 获取当前最适合攻击的目标
  1253. /// </summary>
  1254. /// <param name="skill"></param>
  1255. /// <param name="reason"></param>
  1256. /// <param name="directionChange"></param>
  1257. /// <returns></returns>
  1258. public InstanceUnit getSkillAttackableFirstTarget(SkillTemplate skill, AttackReason reason, ref bool directionChange)
  1259. {
  1260. using (var list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  1261. {
  1262. getSkillAttackableTargets(skill, list, reason);
  1263. if (list.Count > 0)
  1264. {
  1265. float rg = GetSkillAttackRange(skill);
  1266. // 检测攻击范围内的单位 //
  1267. float dr = skill.AttackAngle / 2;
  1268. for (int i = 0; i < list.Count; i++)
  1269. {
  1270. InstanceUnit u = list[i];
  1271. if (Collider.Object_HitBody_TouchFan(u, X, Y, rg, Direction - dr, Direction + dr))
  1272. {
  1273. directionChange = false;
  1274. return u;
  1275. }
  1276. }
  1277. // 优先当前朝向的目标 //
  1278. dr = CMath.PI_DIV_2;
  1279. directionChange = true;
  1280. for (int i = 0; i < list.Count; i++)
  1281. {
  1282. InstanceUnit u = list[i];
  1283. if (Collider.Object_HitBody_TouchFan(u, X, Y, rg, Direction - dr, Direction + dr))
  1284. {
  1285. return u;
  1286. }
  1287. }
  1288. // 最后选取最近的目标 //
  1289. InstanceUnit min = null;
  1290. float min_len = float.MaxValue;
  1291. for (int i = 0; i < list.Count; i++)
  1292. {
  1293. InstanceUnit u = list[i];
  1294. float len = MathVector.getDistanceSquare(u.X, u.Y, X, Y);
  1295. if (min_len > len)
  1296. {
  1297. min_len = len;
  1298. min = u;
  1299. }
  1300. }
  1301. return min;
  1302. }
  1303. }
  1304. return null;
  1305. }
  1306. public struct LaunchSkillParam
  1307. {
  1308. public uint TargetUnitID;
  1309. public Vector2 SpellTargetPos;
  1310. public bool AutoFocusNearTarget;
  1311. public bool LaunchSetDirection; // 释放时是否重新设置方向
  1312. public float direction;
  1313. public bool IsAutoLaunch; // 是否自动战斗时释放
  1314. public bool IsInGuard; // 是否是自动战斗
  1315. public LaunchSkillParam(uint targetUnitID = 0, Vector2 target_pos = null, bool autoFocusNearTarget = false,
  1316. bool LaunchSetDirection = false, float direction = 0, bool IsAutoLaunch = false, bool IsInGuard = false)
  1317. {
  1318. this.TargetUnitID = targetUnitID;
  1319. this.SpellTargetPos = target_pos;
  1320. this.AutoFocusNearTarget = autoFocusNearTarget;
  1321. this.LaunchSetDirection = LaunchSetDirection;
  1322. this.direction = direction;
  1323. this.IsAutoLaunch = IsAutoLaunch;
  1324. this.IsInGuard = IsInGuard;
  1325. }
  1326. }
  1327. public StateSkill launchSkill(SkillState ss, LaunchSkillParam param)
  1328. {
  1329. if (ss == null) return null;
  1330. StateSkill current = CurrentState as StateSkill;
  1331. if (current != null && current.SkillData.IsManuallyCancelable)
  1332. {
  1333. //如果当前技能为手动取消//
  1334. if (current.Skill.ID == ss.ID)
  1335. {
  1336. //判断停止当前技能//
  1337. if (current.IsCancelableBySkill)
  1338. {
  1339. current.block();
  1340. }
  1341. }
  1342. //手动取消技能禁止其他技能打断//
  1343. return null;
  1344. }
  1345. if (mFormula.TryLaunchSkill(this, ss, ref param) && ss.TryLaunch())
  1346. {
  1347. if(param.IsAutoLaunch && !ss.CanAutoLaunch())
  1348. {
  1349. return null;
  1350. }
  1351. //沉默不能释放其他技能//
  1352. if (IsSilent && ss != mDefaultSkill)
  1353. {
  1354. return null;
  1355. }
  1356. // 自动战斗下,释放技能要在范围内
  1357. InstanceUnit target = null;
  1358. if (ss.Data.AttackMustBeInRange)
  1359. {
  1360. target = Parent.getUnit(param.TargetUnitID);
  1361. if (!ss.checkTargetRange(target))
  1362. {
  1363. return null;
  1364. }
  1365. }
  1366. //是否在合理的攻击范围内
  1367. if(param.IsInGuard && !ss.checkTargetInAttackRange(target, param))
  1368. {
  1369. return null;
  1370. }
  1371. if (ss.GetSkillType() == XmdsSkillType.petGiveAcitve)
  1372. {
  1373. mFormula.TriggerPetSkill(this, ss, ref param);
  1374. return null;
  1375. }
  1376. StateSkill state = new StateSkill(this, ss, param, ss.ActionSpeed, (st) =>
  1377. {
  1378. overLaunchSkill(ss, st);
  1379. if (mOnLaunchSkill != null)
  1380. {
  1381. mOnLaunchSkill.Invoke(this, ss);
  1382. }
  1383. });
  1384. if (state.tryLaunch())
  1385. {
  1386. this.Virtual.SetCombatState(BattleStatus.ReadyBattle);
  1387. Parent.cb_unitLaunchSkill(this, ss);
  1388. if (changeState(state))
  1389. {
  1390. //释放成功
  1391. if (param.LaunchSetDirection)
  1392. {
  1393. //Console.WriteLine("launchSkill - 设置方向: " + param.direction + ", " + this.ID);
  1394. //this.faceTo(param.direction);
  1395. //this.SendForceSync();
  1396. }
  1397. return state;
  1398. }
  1399. }
  1400. }
  1401. return null;
  1402. }
  1403. protected virtual void overLaunchSkill(SkillState ss, StateSkill state)
  1404. {
  1405. this.AddHP(-ss.Data.CostHP, null);
  1406. this.AddMP(-ss.Data.CostMP, null);
  1407. }
  1408. /// <summary>
  1409. /// 单位释放技能
  1410. /// </summary>
  1411. public StateSkill launchSkill(int skillID, LaunchSkillParam param)
  1412. {
  1413. SkillState skill = getSkillState(skillID);
  1414. return launchSkill(skill, param);
  1415. }
  1416. /// <summary>
  1417. /// 释放随机技能,一般用于AI
  1418. /// </summary>
  1419. /// <param name="expectTarget"></param>
  1420. /// <param name="param"></param>
  1421. /// <returns></returns>
  1422. public virtual StateSkill launchRandomSkill(SkillTemplate.CastTarget expectTarget, LaunchSkillParam param)
  1423. {
  1424. StateSkill current = CurrentState as StateSkill;
  1425. if (current != null && !current.IsCancelableBySkill)
  1426. {
  1427. return null;
  1428. }
  1429. int rand = RandomN.Next(0, mAllSkills.Count);
  1430. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1431. {
  1432. SkillTemplate st = mAllSkills[CMath.cycNum(rand, si, mAllSkills.Count)];
  1433. if (st.ExpectTarget == expectTarget)
  1434. {
  1435. SkillState sst = mSkillStatus.Get(st.GetID());
  1436. if (sst.LaunchSkill.AutoLaunch && sst.TryLaunch())
  1437. {
  1438. StateSkill state = launchSkill(sst, param);
  1439. if (state != null)
  1440. {
  1441. return state;
  1442. }
  1443. }
  1444. }
  1445. }
  1446. return null;
  1447. }
  1448. public virtual StateSkill launchRandomSkillForAll(LaunchSkillParam param)
  1449. {
  1450. StateSkill current = CurrentState as StateSkill;
  1451. if (current != null && !current.IsCancelableBySkill)
  1452. {
  1453. return null;
  1454. }
  1455. int rand = RandomN.Next(0, mAllSkills.Count);
  1456. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1457. {
  1458. SkillTemplate st = mAllSkills[CMath.cycNum(rand, si, mAllSkills.Count)];
  1459. SkillState sst = mSkillStatus.Get(st.GetID());
  1460. if (sst.LaunchSkill.AutoLaunch && sst.TryLaunch())
  1461. {
  1462. StateSkill state = launchSkill(sst, param);
  1463. if (state != null)
  1464. {
  1465. return state;
  1466. }
  1467. }
  1468. }
  1469. return null;
  1470. }
  1471. /// <summary>
  1472. /// 尝试取消当前技能,打出连击
  1473. /// </summary>
  1474. /// <param name="target"></param>
  1475. /// <param name="autoFocusNearTarget"></param>
  1476. /// <returns></returns>
  1477. public virtual bool tryLaunchRandomSkillAndCancelCurrentSkill(InstanceUnit target, bool autoFocusNearTarget = false)
  1478. {
  1479. StateSkill current = CurrentState as StateSkill;
  1480. if (current != null && !current.IsChanting && current.IsCancelableBySkill)
  1481. {
  1482. LaunchSkillParam param = new LaunchSkillParam(target.ID, null, autoFocusNearTarget);
  1483. //优先多段攻击//
  1484. if (current.SkillData.IsSingleAction)
  1485. {
  1486. if (IsTargetInSkillRange(current.SkillData, target))
  1487. {
  1488. StateSkill st = launchSkill(current.SkillData.ID, param);
  1489. if (st != null)
  1490. {
  1491. return true;
  1492. }
  1493. }
  1494. }
  1495. //随机其他技能//
  1496. int rand = RandomN.Next(0, mAllSkills.Count);
  1497. for (int si = mAllSkills.Count - 1; si >= 0; --si)
  1498. {
  1499. SkillTemplate st = mAllSkills[CMath.cycNum(rand, si, mAllSkills.Count)];
  1500. if (Parent.IsAttackable(this, target, st.ExpectTarget, AttackReason.Attack, st))
  1501. {
  1502. SkillState sst = mSkillStatus.Get(st.GetID());
  1503. if (sst.LaunchSkill.AutoLaunch && IsTargetInSkillRange(st, target))
  1504. {
  1505. StateSkill state = launchSkill(sst, param);
  1506. if (state != null)
  1507. {
  1508. return true;
  1509. }
  1510. }
  1511. }
  1512. }
  1513. }
  1514. return false;
  1515. }
  1516. /// <summary>
  1517. /// 尝试在范围内找到目标释放技能,并进入StateFollowAndAttack,自己走过去打。
  1518. /// </summary>
  1519. /// <param name="range"></param>
  1520. /// <param name="skill_auto_launchable"></param>
  1521. /// <returns></returns>
  1522. public virtual bool tryFollowAndLaunchRandomSkillToTargetInRange(float range, bool skill_auto_launchable = false)
  1523. {
  1524. if (!IsNoneSkill)
  1525. {
  1526. SkillState[] skills = mSkillStatus.SkillsArray;
  1527. CUtils.RandomArray(RandomN, skills);
  1528. using (var list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  1529. {
  1530. //随机找个目标施法//
  1531. Parent.getObjectsRoundRange<InstanceUnit>(Collider.Object_Pos_IncludeInRound, X, Y, Info.GuardRange, list , this.AoiStatus);
  1532. DoAndRemoveCollection.UpdateAndRemove<InstanceUnit>(list, (InstanceUnit u) =>
  1533. {
  1534. return !u.IsActive;
  1535. });
  1536. if (list.Count == 0) { return false; }
  1537. CUtils.RandomList(Parent.RandomN, list);
  1538. foreach (SkillState skill in skills)
  1539. {
  1540. if ((!skill_auto_launchable || skill.LaunchSkill.AutoLaunch) && skill.TryLaunch())
  1541. {
  1542. for (int i = 0; i < list.Count; i++)
  1543. {
  1544. InstanceUnit u = list[i];
  1545. if (Parent.IsAttackable(this, u, skill.Data.ExpectTarget, AttackReason.Attack, skill.Data))
  1546. {
  1547. //检测是否有可释放技能//
  1548. changeState(new StateFollowAndAttack(this, u, skill.Data.ExpectTarget));
  1549. return true;
  1550. }
  1551. }
  1552. }
  1553. }
  1554. }
  1555. }
  1556. return false;
  1557. }
  1558. #endregion
  1559. //-----------------------------------------------------------------------------------------------------------------
  1560. internal void deadDropItems(int force)
  1561. {
  1562. foreach (KeyValuePair<ItemTemplate, DropItem> e in mDropItems.Drop(Parent, Parent.RandomN))
  1563. {
  1564. float x;
  1565. float y;
  1566. CMath.RandomPosInRound(RandomN, X, Y, e.Value.DropPosRange, out x, out y);
  1567. Parent.AddItem(e.Key, e.Key.Name, x, y, CMath.RandomAngle(RandomN), force, e.Key.Name, this);
  1568. }
  1569. }
  1570. protected bool tryPickObject(InstanceUnit unit)
  1571. {
  1572. if (!Parent.IsVisibleAOI(this, unit))
  1573. {
  1574. return false;
  1575. }
  1576. bool ret = true;
  1577. if (mOnTryPickUnit != null)
  1578. {
  1579. foreach (TryPickUnitHandler trypick in mOnTryPickUnit.GetInvocationList())
  1580. {
  1581. if (!trypick.Invoke(this, unit))
  1582. {
  1583. ret = false;
  1584. }
  1585. }
  1586. }
  1587. return ret;
  1588. }
  1589. public void PickUnit(InstanceUnit pickable)
  1590. {
  1591. if (tryPickObject(pickable))
  1592. {
  1593. Parent.cb_unitPickUnitCallBack(this, pickable);
  1594. if (mOnPickUnit != null)
  1595. {
  1596. mOnPickUnit.Invoke(this, pickable);
  1597. }
  1598. }
  1599. }
  1600. public CommonAI.Data.SceneType GetSceneType()
  1601. {
  1602. return mZone.SceneType;
  1603. }
  1604. //-----------------------------------------------------------------------------------------------------//
  1605. #region Environment
  1606. //-----------------------------------------------------------------------------------------------------//
  1607. private HashMap<string, EnvironmentVar> EnvironmentVarMap = new HashMap<string, EnvironmentVar>();
  1608. public void SetEnvironmentVar(string key, object value, bool syncToClient = false)
  1609. {
  1610. if (!string.IsNullOrEmpty(key))
  1611. {
  1612. EnvironmentVar var = EnvironmentVarMap.Get(key);
  1613. if (var != null)
  1614. {
  1615. if (EnvironmentVar.ALWAYS_SYNC_ENVIRONMENT_VAR || (var.SyncToClient && var.Value != value))
  1616. {
  1617. queueEvent(new PlayerSyncEnvironmentVarEvent(ID, key, value));
  1618. }
  1619. var.Value = value;
  1620. }
  1621. else
  1622. {
  1623. var = new EnvironmentVar(key, syncToClient, value);
  1624. EnvironmentVarMap.Add(key, var);
  1625. if (EnvironmentVar.ALWAYS_SYNC_ENVIRONMENT_VAR || var.SyncToClient)
  1626. {
  1627. queueEvent(new PlayerSyncEnvironmentVarEvent(ID, key, value));
  1628. }
  1629. }
  1630. }
  1631. }
  1632. public T GetEnvironmentVarAs<T>(string key)
  1633. {
  1634. if (!string.IsNullOrEmpty(key))
  1635. {
  1636. EnvironmentVar var = EnvironmentVarMap.Get(key);
  1637. if (var != null)
  1638. {
  1639. try
  1640. {
  1641. return (T)var.Value;
  1642. }
  1643. catch (Exception err)
  1644. {
  1645. log.Warn("GetEnvironmentVarAs : " + key + ", catch: " + err);
  1646. }
  1647. }
  1648. }
  1649. return default(T);
  1650. }
  1651. public int ListEnvironmentVars(List<EnvironmentVar> list)
  1652. {
  1653. list.AddRange(EnvironmentVarMap.Values);
  1654. return EnvironmentVarMap.Count;
  1655. }
  1656. public List<EnvironmentVar> ListEnvironmentVars()
  1657. {
  1658. return new List<EnvironmentVar>(EnvironmentVarMap.Values);
  1659. }
  1660. public ClientStruct.ZoneEnvironmentVar[] GetCurrentUnitVars()
  1661. {
  1662. ClientStruct.ZoneEnvironmentVar[] ret = new ClientStruct.ZoneEnvironmentVar[EnvironmentVarMap.Count];
  1663. int i = 0;
  1664. try
  1665. {
  1666. foreach (EnvironmentVar var in EnvironmentVarMap.Values)
  1667. {
  1668. ret[i].Key = var.Key;
  1669. ret[i].Value = var.Value;
  1670. ret[i].SyncToClient = var.SyncToClient;
  1671. i++;
  1672. }
  1673. }
  1674. catch(Exception e)
  1675. {
  1676. log.Warn("GetCurrentUnitVars catch: " + ret.Length + ", " + EnvironmentVarMap.Count + ", " + i + ", e: " + e);
  1677. }
  1678. return ret;
  1679. }
  1680. #endregion
  1681. //-----------------------------------------------------------------------------------------------------//
  1682. //-----------------------------------------------------------------------------------------------------//
  1683. #region SceneEvents
  1684. //-----------------------------------------------------------------------------------------------------//
  1685. private HashMap<int, UnitEventTriggerCollection> mBindEvents = new HashMap<int, UnitEventTriggerCollection>();
  1686. public void BindUnitEvent(int unit_event_id)
  1687. {
  1688. if (!mBindEvents.ContainsKey(unit_event_id))
  1689. {
  1690. UnitEventTemplate uet = Templates.getUnitEvent(unit_event_id);
  1691. if (uet != null)
  1692. {
  1693. uet = uet.Clone() as UnitEventTemplate;
  1694. UnitEventTriggerCollection bind_event = new UnitEventTriggerCollection(this);
  1695. bind_event.Bind(uet.Events);
  1696. mBindEvents.Add(unit_event_id, bind_event);
  1697. }
  1698. }
  1699. }
  1700. protected virtual void clearBindEvents()
  1701. {
  1702. foreach (var evt in mBindEvents.Values)
  1703. {
  1704. evt.Dispose();
  1705. }
  1706. mBindEvents.Clear();
  1707. }
  1708. #endregion
  1709. //-----------------------------------------------------------------------------------------------------//
  1710. //-----------------------------------------------------------------------------------------------------//
  1711. }
  1712. }