Desktop Java

Tower Defense in JavaFX (3)

In the last part you saw how you can create Sprites, animate them, and give them Behavior. But the animation isn’t very nice, because as an Insectoid you’re supposed to always look where you fly. Remember: Safety first! We can do that very easily by creating a custom TileSetAnimation:
 
 
 
 
 
 
 

public class RotatingTileSetAnimation extends TileSetAnimation {

private double angle = 0;

public RotatingTileSetAnimation(TileSet set, int[] indices, float speed) {
super(set, indices, speed);
}

public void setAngle(double angle) {
this.angle = angle;
}

@Override
public void render(Sprite sprite, GraphicsContext context, float alpha, long delta) {
context.save();
context.translate(sprite.getWidth() / 2, sprite.getHeight() / 2);
context.rotate(angle);
context.translate(-sprite.getWidth() / 2, -sprite.getHeight() / 2);
super.render(sprite, context, alpha, delta); //To change body of generated methods, choose Tools | Templates.
context.restore();
}
}

We can calculate the rotation angle from the x and y velocity and set it on our GraphicsContext before rendering. So here’s a subclass that does that:

public class LookAheadTileSetAnimation extends RotatingTileSetAnimation {

public LookAheadTileSetAnimation(TileSet set, int[] indices, float speed) {
super(set, indices, speed);
}

@Override
public void render(Sprite sprite, GraphicsContext context, float alpha, long delta) {
setAngle(Math.toDegrees(Math.atan2(sprite.getVelocityY(), sprite.getVelocityX())));
super.render(sprite, context, alpha, delta); //To change body of generated methods, choose Tools | Templates.
}
}

Here’s the result:

Fairly simple, isn’t it? Now the next step will be to add some behavior to the turets themselves. I want them to always check for the closest enemy and point the cannon at it. First I changed the code a bit and separated the turrets into bases and cannons again. So when you select a cannon now, a turret-base will be placed in the TileLayer named “turret-bases”. I simply changed the TurretView class to support this:

class TileSetView extends StackPane {

Canvas canvas;
TileSet cannons;
TileSet bases;
int selectedIndex = 0;
Color selected = Color.rgb(100, 100, 255, .2);

public TileSetView() {
}

public void setTileSet(final TileSet bases, final TileSet cannons) {
this.cannons = cannons;
this.bases = bases;
getChildren().clear();
ImageView turretBases = new ImageView();
turretBases.setImage(bases.getTileImage());

ImageView turretCannons = new ImageView();
turretCannons.setImage(cannons.getTileImage());

getChildren().addAll(turretBases, turretCannons);

canvas = new Canvas(cannons.getTileImage().getWidth(), cannons.getTileImage().getHeight());
getChildren().add(canvas);
canvas.setOnMouseClicked(new EventHandler() {
@Override
public void handle(MouseEvent t) {
double x = t.getX();
double y = t.getY();
selectedIndex = (int) ((int) x / cannons.getTilewidth() + (((int) y / cannons.getTileheight()) * cannons.getNumColumns()));
updateCanvas();
}
});
updateCanvas();
}

public int getSelectedGid() {
if (bases == null) {
return -1;
}
return bases.getFirstgid() + selectedIndex;
}

public int getSelectedIndex(){
return selectedIndex;
}

public void updateCanvas() {
GraphicsContext graphicsContext2D = canvas.getGraphicsContext2D();
graphicsContext2D.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
if (selectedIndex >= 0) {
graphicsContext2D.setFill(selected);
int x = selectedIndex % cannons.getNumColumns();
int y = selectedIndex / cannons.getNumColumns();
graphicsContext2D.fillRect(x * cannons.getTilewidth(), y * cannons.getTileheight(), cannons.getTilewidth(), cannons.getTileheight());
}
}
}

So this is what it looks like now:

Next we add the cannons. While the turret-bases are simpel Tiles, our Cannons need to be Sprites, so we can add Behavior to them:

public class CannonSprite extends Sprite {

RotatingTileSetAnimation rotateAnimation;

public CannonSprite(GameCanvas parent, RotatingTileSetAnimation animation, String name, double x, double y, int width, int height) {
super(parent, animation, name, x, y, width, height, Lookup.EMPTY);
this.rotateAnimation = animation;
addBehaviour(new SpriteBehavior() {
@Override
public boolean perform(Sprite sprite) {
Sprite closest = null;
double dist = Double.MAX_VALUE;
Collection sprites = sprite.getParent().getSprites();
for (Sprite sprite1 : sprites) {
if (sprite1 instanceof EnemySprite) {
double distance = distance(getX(), getY(), sprite1.getX(), sprite1.getY());
if (distance < dist) {
dist = distance;
closest = sprite1;
}
}
}
if (closest != null) {
rotateAnimation.setAngle(Math.toDegrees(Math.atan2(closest.getY() - sprite.getY(),closest.getX() - sprite.getX())));
}

return true;
}
});
}

public double distance(double x1, double y1, double x2, double y2) {
return Math.sqrt(
(x1 - x2) * (x1 - x2)
+ (y1 - y2) * (y1 - y2));
}
}

Again I’m using a RotatingTileSetAnimation and simply set the angle so the cannon points at the closest Enemy. Here’s what we get:

That’s it for this part of the tutorial. We’ve created some custom animations to make the Insectoids look in the right direction and also to make the Turrets always point at the closes target. As you can see from these examples, the Game Engine tries to make it really simple to add Behavior to the Sprites. In the next part we’ll make the turrets fire at their Enemies.
 

Reference: Tower Defense in JavaFX (3) from our JCG partner Toni Epple at the Eppleton blog.

Toni Epple

Anton is a consultant worldwide for a wide variety of companies, ranging from startups to Fortune 500 companies, in many areas, including finance institutions and aerospace. His main interest is Client side development, and he has authored books and numerous articles on this topic. He is a member of the NetBeans Dream Team and a Oracle Java Champion. In 2013 he was elected as a JavaONE Rockstar, in 2014 he received a Duke’s Choice Award for his work on DukeScript.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button