DefaultHealth.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. package me.hammerle.supersnuvi.entity.components;
  2. import me.hammerle.supersnuvi.Game;
  3. import me.hammerle.supersnuvi.entity.Entity;
  4. import me.hammerle.supersnuvi.tiles.Tile;
  5. import me.hammerle.supersnuvi.util.SoundUtils;
  6. import me.hammerle.supersnuvi.util.SoundUtils.Sound;
  7. public class DefaultHealth extends Health
  8. {
  9. private final float maxHealth;
  10. private float health;
  11. private int hurtTicks = 0;
  12. private int invincibility = 0;
  13. private final IDeath death;
  14. private final Sound soundHeal;
  15. private final Sound soundHurt;
  16. private final Sound soundDeath;
  17. public DefaultHealth(Entity ent, IDeath death, float maxHealth,
  18. Sound soundHeal, Sound soundHurt, Sound soundDeath)
  19. {
  20. super(ent);
  21. this.death = death;
  22. this.maxHealth = maxHealth;
  23. this.health = maxHealth;
  24. this.soundHeal = soundHeal;
  25. this.soundHurt = soundHurt;
  26. this.soundDeath = soundDeath;
  27. }
  28. @Override
  29. public void tick()
  30. {
  31. if(invincibility > 0)
  32. {
  33. invincibility--;
  34. }
  35. if(hurtTicks > 0)
  36. {
  37. hurtTicks--;
  38. }
  39. else if(hurtTicks < 0)
  40. {
  41. hurtTicks++;
  42. }
  43. if(shouldDespawn())
  44. {
  45. death.onDeath(ent);
  46. }
  47. }
  48. @Override
  49. public boolean isDead()
  50. {
  51. return health <= 0.0f;
  52. }
  53. @Override
  54. public boolean shouldDespawn()
  55. {
  56. return (isDead() && !ent.isAnimated()) || (ent.getY() > ent.getLevel().getHeight() * Tile.SIZE);
  57. }
  58. @Override
  59. public boolean wasHurt()
  60. {
  61. return hurtTicks > 0;
  62. }
  63. @Override
  64. public boolean wasHealed()
  65. {
  66. return hurtTicks < 0;
  67. }
  68. @Override
  69. public float getMaxHealth()
  70. {
  71. return maxHealth;
  72. }
  73. @Override
  74. public float getHealth()
  75. {
  76. return health;
  77. }
  78. @Override
  79. public void addHealth(float h)
  80. {
  81. if(h < 0)
  82. {
  83. if(invincibility > 0)
  84. {
  85. return;
  86. }
  87. invincibility = Game.getTicksForMillis(1000);
  88. hurtTicks = Game.getTicksForMillis(500);
  89. SoundUtils.playSound(soundHurt);
  90. }
  91. else
  92. {
  93. hurtTicks = -Game.getTicksForMillis(250);
  94. SoundUtils.playSound(soundHeal);
  95. }
  96. health += h;
  97. if(health > maxHealth)
  98. {
  99. health = maxHealth;
  100. }
  101. else if(health < 0.0f)
  102. {
  103. health = 0.0f;
  104. SoundUtils.playSound(soundDeath);
  105. }
  106. }
  107. }