I'm having a hard time getting a tower to attack spawned units. Trying to get it to attack a unit when it sees it in a certain radius, but keeps giving me an index out of bounds error for it, so it stops the game.
here's the coding for the tower i have:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
* Write a description of class fasttower here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class fasttower extends tower
{
/**
* Act - do whatever the fasttower wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
//att lv 1/2/3 1/2/4/8
//att spd lv 1/2/3 1/.75/.5/.35
//price 5
//upgrade price 10
private int attack = 1;
private long attspd = 1000; //milliseconds
private int range = 5;
private int lvl = 1;
private long count = 0;
private long aTime = 0;
private int wave = 1; //have wave class come in as well
public void act()
{
// Add your action code here.
//use getObjectsInRange() method for actors to make a radius for towers
update();
attack();
}
private void attack()
{
List<enemies> e = getObjectsInRange(5, enemies.class);//change radius to variable for when
//upgrading to up radius.
if(e !=null)
{
/** attack first enemy.
* if(clock)
* {
* e(0).health - attack;
*}
*
**/
//int index = e.indexOf(enemies.class);
enemies temp = e.get(0);
double hp = temp.getHealth();
if(clock())
{
hp -= attack;
}
if(hp <= 0)
{
((tdpath)getWorld()).removeObject(temp);
// minerals+= whatever the value is for the monster.
}
}
}
private void update()
{
/**if have minerals and click on tower, upgrade to next lv
* will have to add a minerals class and have it seen in every class.
*if(minerals == 10 && clickontower && (lv <= 4))
*{
* lvl++;
* attack += (attack*lvl);
* attspd = attspd - 200;
* range += (range*lvl);
*}
**/
}
//says when to attack based on milliseconds (1000 = 1 sec, so every second for this tower unless
//it's upgraded)
private boolean clock()
{
long time = System.currentTimeMillis();
if(count!=0)
{
long temp = time - count;
aTime = temp;
}
count = time;
if(aTime >= 1000 && lvl == 1)
{
aTime = 0;
return true;
}
if(aTime >= (1000 -(lvl*100)) && lvl > 1)
{
aTime = 0;
return true;
}
return false;
}
}
