TargetableObject.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //------------------------------------------------------------
  2. // Game Framework
  3. // Copyright © 2013-2021 Jiang Yin. All rights reserved.
  4. // Homepage: https://gameframework.cn/
  5. // Feedback: mailto:ellan@gameframework.cn
  6. //------------------------------------------------------------
  7. using UnityEngine;
  8. using UnityGameFramework.Runtime;
  9. namespace MetaClient
  10. {
  11. /// <summary>
  12. /// 可作为目标的实体类。
  13. /// </summary>
  14. public abstract class TargetableObject : Entity
  15. {
  16. [SerializeField]
  17. private TargetableObjectData m_TargetableObjectData = null;
  18. public bool IsDead
  19. {
  20. get
  21. {
  22. return m_TargetableObjectData.HP <= 0;
  23. }
  24. }
  25. public abstract ImpactData GetImpactData();
  26. public void ApplyDamage(Entity attacker, int damageHP)
  27. {
  28. float fromHPRatio = m_TargetableObjectData.HPRatio;
  29. m_TargetableObjectData.HP -= damageHP;
  30. float toHPRatio = m_TargetableObjectData.HPRatio;
  31. if (fromHPRatio > toHPRatio)
  32. {
  33. GameEntry.HPBar.ShowHPBar(this, fromHPRatio, toHPRatio);
  34. }
  35. if (m_TargetableObjectData.HP <= 0)
  36. {
  37. OnDead(attacker);
  38. }
  39. }
  40. #if UNITY_2017_3_OR_NEWER
  41. protected override void OnInit(object userData)
  42. #else
  43. protected internal override void OnInit(object userData)
  44. #endif
  45. {
  46. base.OnInit(userData);
  47. gameObject.SetLayerRecursively(Constant.Layer.TargetableObjectLayerId);
  48. }
  49. #if UNITY_2017_3_OR_NEWER
  50. protected override void OnShow(object userData)
  51. #else
  52. protected internal override void OnShow(object userData)
  53. #endif
  54. {
  55. base.OnShow(userData);
  56. m_TargetableObjectData = userData as TargetableObjectData;
  57. if (m_TargetableObjectData == null)
  58. {
  59. Log.Error("Targetable object data is invalid.");
  60. return;
  61. }
  62. }
  63. protected virtual void OnDead(Entity attacker)
  64. {
  65. GameEntry.Entity.HideEntity(this);
  66. }
  67. private void OnTriggerEnter(Collider other)
  68. {
  69. Entity entity = other.gameObject.GetComponent<Entity>();
  70. if (entity == null)
  71. {
  72. return;
  73. }
  74. if (entity is TargetableObject && entity.Id >= Id)
  75. {
  76. // 碰撞事件由 Id 小的一方处理,避免重复处理
  77. return;
  78. }
  79. AIUtility.PerformCollision(this, entity);
  80. }
  81. }
  82. }