Game Development Reference
In-Depth Information
self.scaleX = enemy.hitPoints / (float)enemy.initialHitPoints;
else if (self.visible)
self.visible = NO;
The healthbar turns its visible state on and off to be in line with its parent Enemy ob-
ject. The reset method places the healthbar sprite at the proper location just above
the head of the Enemy 's sprite. Because the healthbar is a child of the enemy, it only
needs to be offset from the enemy sprite's 0,0 position (lower left-hand corner by de-
fault). And because a decrease in health is displayed by modifying the scaleX prop-
erty, it, too, needs to be reset to its default scale.
In the update method, and only when its parent is visible, the HealthbarCom-
ponent first asserts that the parent is of the class Enemy . Because this component re-
lies on certain properties only available in the Enemy class and its subclasses, you
need to make sure that it's the right parent class. Modify the scaleX property as a
percentage of the current hit points divided by the initial hit points. Because there's
currently no way of telling when exactly the hit points changed, the calculation is done
every frame, regardless of whether it's needed. The overhead here is minimal, but for
more complex calculations, a call to the HealthbarComponent from the onHit
method of the Enemy class would be preferable.
Caution The enemy.initialHitPoints divisor is cast to float .
Otherwise, the division would be an integer division that would always result in
0 because integers can't represent fractional numbers and are always rounded
down. Casting the divisor to a f l oat data type ensures that the division is done
with floating-point precision, and therefore the result is a floating-point value.
In the init method of the Enemy class, the HealthbarComponent is added
alongside the other components, but only if the enemy type is EnemyTypeBoss :
Search Nedrilad ::

Custom Search