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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


5 − one =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close