Tower Defense in JavaFX (5)

This is part 5 of this ongoing tutorial on creating a Tower Defense Game in JavaFX using the FXGameEngine. The enemies now fly on their attack path to the target, and the Turrets aim and shoot at them. So the most important parts are there, but there are still a lot of details missing. The game simply starts and doesn’t give us a chance to prepare for the next wave. It doesn’t show the score (actually there is no score yet). The wave does never end, and you can’t win or loose. So we need to add some game logic a HUD and Controls. We also need to see the damage status of the Enemies. The last one is the feature, we’ll care about in this part of the tutorial.

StackedRenderer

So let’s start with the Enemy status. We could add those in an extra HUD Layer, since that’s what a HUD is for, but I prepare to do it via Renderers. Every Sprite has one current Renderer. You can switch Renderers, and that’s what SpriteActions do (we’ll treat those in a different tutorial), but you still can only have one active Renderer at once. In our EnemySprite it’s the LookAheadTileSetAnimation. In order to allow a combination of Renderers, you can use the StackedRenderer class. It allows you to stack an unlimited number of Renderers, and simply delegates to them on every method call.

So we can create a simple HealthBarRenderer and use that:

public class HealthBarRenderer implements Renderer {

@Override
public boolean prepare(Sprite sprite, long time) {
return true;
}

@Override
public void render(Sprite sprite, GraphicsContext context, float alpha, long time) {
EnemySprite enemySprite = (EnemySprite) sprite;
double health = enemySprite.getHealth();
double maxHealth = enemySprite.getMaxHealth();
if (health == maxHealth) {
return;
}

int width = sprite.getWidth();
int height = sprite.getHeight();
double percent = health / maxHealth;
context.setFill( Color.rgb(200,200,200,.5));
context.fillRect(4+(width / 2), 10+(height / 2), (width / 2), 4);

context.setFill( Color.rgb(0,255,0,.5));
if (percent < .5) {
context.setFill(Color.rgb(255,255,0,.5));
}
if (percent < .2) {
context.setFill(Color.rgb(255,0,0,0.5));
}
context.fillRect(4+(width / 2), 10+(height / 2), (width / 2 * percent), 4);
}
}

And we use that in a StackedRenderer:

        final TileSetAnimation tileSetAnimation = new LookAheadTileSetAnimation(enemy1, new int[]{0, 1, 2, 3, 4, 5}, 10f);
final StackedRenderer stacked = new StackedRenderer(tileSetAnimation, new HealthBarRenderer());

And this is what we get:

In the next part we’ll add the HUD.

Dieser Eintrag wurde in javafx geschrieben. Link merken.

Hinterlasse eine Antwort

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *

Du kannst folgende HTML-Tags benutzen: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>