• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0

First try at Tower Defense

0 posts in this topic

I tried making this tower defense game. I've made a lot of bugs in my code, and I really need some help. I'm new, and I'm basically stuck. It's been days, in fact. Please note that I'm using JMonkeyEngine 3.0, so I hope you guys are familiar with working with this engine. Please note that this is not complete, so that's why you may see some useless variables.


Let me explain what it basically it. Everything is made out of cubes even the floor, so we have a base which is a rectangle, and cubes moving towards it. I've got that part finished, and on both sides of the path we have two rectangular towers. The user clicks on one to select them, and presses "c" to give them a charge. A charge is basically an ammo packet, and each charge has 5 bullets.


Here's the code for a charge:


package mygame;

public class Charges {
    private int damage = 5;
    private int bullets = 5;

    public int getDamage() {
        return damage;

    public int getRemainingShots() {
        return bullets;

Here is the class with all the main methods, and I believe everything is in order in this class. I might be wrong, though.


package mygame;

import com.jme3.app.SimpleApplication;
import com.jme3.app.state.AppState;
import com.jme3.collision.CollisionResults;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.input.controls.Trigger;
import com.jme3.math.Ray;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.scene.Geometry;
import com.jme3.system.AppSettings;
import java.util.ArrayList;

public class Main extends SimpleApplication {
    private static final String MAPPING_SELECT_TOWER = "Select Tower";
    private static final String MAPPING_CHARGE_TOWER = "Charge Tower";
    private static final Trigger TRIGGER_LEFT_CLICK = new MouseButtonTrigger(MouseInput.BUTTON_LEFT);
    private static final Trigger TRIGGER_KEY_C = new KeyTrigger(KeyInput.KEY_C);
    private TowerControl selected = null;

    public static void main(String[] args) {
        AppSettings settings = new AppSettings(true);
        settings.setTitle("Tower Defense");
        Main app = new Main();

    public void simpleInitApp() {
        GamePlayAppState gamePlay = new GamePlayAppState();
        stateManager.attach((AppState) gamePlay);
        inputManager.addMapping(MAPPING_SELECT_TOWER, TRIGGER_LEFT_CLICK);
        inputManager.addMapping(MAPPING_CHARGE_TOWER, TRIGGER_KEY_C);
        ActionListener selectListener = new ActionListener() {
            public void onAction(String name, boolean isPressed, float tpf) {
                if(name.equals(MAPPING_SELECT_TOWER)) {
                    if(isPressed == false) {
                        CollisionResults results = new CollisionResults();
                        Vector2f click2d = inputManager.getCursorPosition();
                        Vector3f click3d = cam.getWorldCoordinates(new Vector2f(click2d.getX(),
                                                                   click2d.getY()), 0f);
                        Vector3f dir = cam.getWorldCoordinates(new Vector2f(click2d.getX(),
                                                               click2d.getY()), 1f).
                        Ray ray = new Ray(click3d, dir);
                        rootNode.collideWith(ray, results);
                        if(results.getClosestCollision() != null && results.getClosestCollision().getGeometry().
                            getControl(TowerControl.class) != null) {
                            TowerControl tower = results.getClosestCollision().getGeometry().
                            selected = tower;
                            selected = null;
        ActionListener chargeListener = new ActionListener() {
            public void onAction(String name, boolean isPressed, float tpf) {
                if(name.equals(MAPPING_CHARGE_TOWER)) {
                    if(selected != null) {
                        TowerControl tower = selected;
                        ArrayList<Charges> charges = tower.getCharges();
                        charges.add(new Charges());
                        GamePlayAppState gamePlay = new GamePlayAppState();
                        gamePlay.setBudget(gamePlay.getBudget() - 1);
                        selected = null;
        inputManager.addListener(selectListener, MAPPING_SELECT_TOWER);
        inputManager.addListener(chargeListener, MAPPING_CHARGE_TOWER);

    public void simpleUpdate(float tpf) {
        //TODO: add update code

    public void simpleRender(RenderManager rm) {
        //TODO: add render code

As you can see, I am selecting towers by casting a ray from the visible cursor, and not the center of the screen. Now, I believe that the tower is actually receiving charges when I press c. In fact, there is a tower far enough from the enemies(creeps) that if I select, and press c it will shoot a bullet. Another problem arises from here, but I'll get to that later.


Here's the necessary code for the Tower Control:

package mygame;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Geometry;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.shape.Line;
import java.util.ArrayList;
public class TowerControl extends AbstractControl {
    private int chargesNum;
    private int index;
    private int height = 2;
    private GamePlayAppState gamePlay;
    private ArrayList<Charges> charges = new ArrayList<Charges>();
    private ArrayList<Spatial> creeps = new ArrayList<Spatial>();    
    private ArrayList<Spatial> reachables = new ArrayList<Spatial>();
    TowerControl(GamePlayAppState gamePlay, int chargesNum, int index) {
        this.gamePlay = gamePlay;
        this.chargesNum = chargesNum;
        this.index = index;
        this.creeps = gamePlay.getCreeps();
    public void controlUpdate(float tpf) {
        Geometry bullet = null;
        for(Spatial creep: getCreeps()) {
            if(spatial.getLocalTranslation().distance(creep.getLocalTranslation()) < 5) {
        if(getReachables().size() > 0 && charges.size() > 0) {
            for(Spatial creep : getReachables()) {
                int bullets = charges.get(0).getRemainingShots();
                for(int i = bullets; i > 0; i--) {
                    Line line = new Line(spatial.getLocalTranslation().add(0, 3, 0), 
                    bullet = new Geometry("Bullet", line);
                    Material black = new Material(getGamePlay().getAssetManager(),
                    black.setColor("Color", ColorRGBA.Black);


Now, my controlUpdate method is suppose to be repeatedly checking if there is a charge and if so use up the bullets on the nearest creep. I had some trouble on how to do this, but I tried my best. Sadly, an exception is being thrown from line 40, and I've tried so many things. I just can't figure it out.


Here's the stack trace: 

at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at mygame.TowerControl.controlUpdate(TowerControl.java:40)
at com.jme3.scene.control.AbstractControl.update(AbstractControl.java:112)
at com.jme3.scene.Spatial.runControlUpdate(Spatial.java:570)
at com.jme3.scene.Spatial.updateLogicalState(Spatial.java:688)
at com.jme3.scene.Node.updateLogicalState(Node.java:152)
at com.jme3.scene.Node.updateLogicalState(Node.java:152)
at com.jme3.app.SimpleApplication.update(SimpleApplication.java:244)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.runLoop(LwjglAbstractDisplay.java:151)
at com.jme3.system.lwjgl.LwjglDisplay.runLoop(LwjglDisplay.java:185)
at com.jme3.system.lwjgl.LwjglAbstractDisplay.run(LwjglAbstractDisplay.java:228)
at java.lang.Thread.run(Thread.java:744)

Now when I said I could manage to get a bullet to be shot(which is a simple drawn line) it stays there, doesn't detach itself from the rootNode, and doesn't creep the creep no matter what damage, health I set.


package mygame;

import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.control.AbstractControl;

public class CreepControl extends AbstractControl{
    private int health;
    private int index;
    private GamePlayAppState gamePlay;
    CreepControl(GamePlayAppState gamePlay, int health, int index) {
        this.gamePlay = gamePlay;
        this.health = health;
        this.index = index;
    public void controlUpdate(float tpf) {
        if(health > 0)
            spatial.move(0, 0, -tpf);
        else if(health < 0) {
            gamePlay.setBudget(gamePlay.getBudget() + 10);
        if(spatial.getLocalTranslation().z > 0) {
            gamePlay.setHealth(gamePlay.getHealth() - 20);
    public void controlRender(RenderManager rm, ViewPort vp) {

    public int getHealth() {
        return health;

    public void setHealth(int health) {
        this.health = health;

    public int getIndex() {
        return index;

    public void setIndex(int index) {
        this.index = index;

Also, I used if(spatial.getLocalTranslation < 0), so they can detach themselves from the rootNode if that condition is met, but they just keep going on infinitely. 


I'll also show my appState class if that can help in any way.

package mygame;

import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.asset.AssetManager;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import java.util.ArrayList;

public class GamePlayAppState extends AbstractAppState {
    private SimpleApplication app;
    private Node rootNode;
    private AssetManager assetManager;   
    private int health;
    private int level;
    private int budget;
    private int score;
    private ArrayList<Spatial> creeps = new ArrayList<Spatial>();
    private boolean lastGameWon;
    public void initialize(AppStateManager stateManager, Application app) {
        this.setApp((SimpleApplication) app);
        createScene(getRootNode(), getAssetManager());
    public void update(float tpf) {
    public void cleanup() {
    private void createScene(Node rootNode, AssetManager assetManager) {
    Box bFloor = new Box(33, 1, 33);
    Geometry floor = new Geometry("Box", bFloor);
    floor.setLocalTranslation(0, -5, 0);
    Material orange = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    orange.setColor("Color", ColorRGBA.Orange);

    Box bBase = new Box(2.5f, 1, 1);
    Geometry base = new Geometry("Box", bBase);
    Material yellow = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    yellow.setColor("Color", ColorRGBA.Yellow);

    Box bTower = new Box(.4f, 2, .4f);
    Geometry tower = new Geometry("Box", bTower);
    Material green = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    green.setColor("Color", ColorRGBA.Green);
    Geometry tower2 = tower.clone();
    tower.setUserData("chargesNum", 10);
    tower2.setUserData("chargesNum", 10);
    tower.setUserData("index", 0);
    tower2.setUserData("index", 1);
    tower.addControl(new TowerControl(this, 100, 0));
    tower2.addControl(new TowerControl(this, 100, 1));

    Box bCreep = new Box(.4f, .4f, .4f);
    Geometry creep = new Geometry("Box", bCreep);
    Material black = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    black.setColor("Color", ColorRGBA.Black);
    Geometry creep2 = creep.clone();
    Geometry creep3 = creep.clone();
    Geometry creep4 = creep.clone();
    Geometry creep5 = creep.clone();
    Geometry creep6 = creep.clone();
    creep.setUserData("health", 100);
    creep2.setUserData("health", 100);
    creep3.setUserData("health", 100);
    creep4.setUserData("health", 100);
    creep5.setUserData("health", 100);
    creep6.setUserData("health", 100);
    creep.setUserData("index", 0);
    creep2.setUserData("index", 1);
    creep3.setUserData("index", 2);
    creep4.setUserData("index", 3);
    creep5.setUserData("index", 4);
    creep6.setUserData("index", 5);
    creep.addControl(new CreepControl(this, 25, 0));
    creep2.addControl(new CreepControl(this, 25, 1));
    creep3.addControl(new CreepControl(this, 25, 2));
    creep4.addControl(new CreepControl(this, 25, 3));
    creep5.addControl(new CreepControl(this, 25, 4));
    creep6.addControl(new CreepControl(this, 25, 5));

    Node playerNode = new Node();
    Node towerNode = new Node();
    Node creepNode = new Node();

    floor.setLocalTranslation(0, -2, 1);

    tower.setLocalTranslation(-2.2f, 0, 4);
    tower2.setLocalTranslation(2.5f, 0, 5.5f);

    creep.setLocalTranslation(0, -0.6f, 12);
    creep2.setLocalTranslation(1, -0.6f, 9f);
    creep3.setLocalTranslation(-1, -0.6f, 15);
    creep4.setLocalTranslation(1.5f, -0.6f, 18);
    creep5.setLocalTranslation(1.1f, -0.6f, 19);
    creep6.setLocalTranslation(-1.15f, -0.6f, 20);






I'm really begging for help on this, so please help me debug my code on step at a time.




Edited by cooljava50544

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  
Followers 0