This site requires JavaScript, please enable it in your browser!
Greenfoot back
johnsonhwang1008
johnsonhwang1008 wrote ...

2019/10/30

TowerDefense

johnsonhwang1008 johnsonhwang1008

2019/10/30

#
I'm making a tower defense game and Im having trouble with adding a range for a tower and making it aim at the enemy with the . I created a class that created a filled circle public Tower1lvl1(int size) { Color green = new Color(53,199,0); GreenfootImage img = new GreenfootImage(size, size); img.setColor(green); img.fillOval(0, 0, 260, 260); setImage(img); getImage().setTransparency(100); } and I wanted it to be where the tower aims within this range and aim for the Enemy class with the most distance traveled.
Super_Hippo Super_Hippo

2019/10/31

#
If you have a variable in your Enemy class which saves the traveled distance for the actor (increase it by its speed whenever it moves) and a method to return it …
private int distanceTraveled = 0;
public int getDistanceTraveled() {return distanceTraveled;}
… then a tower can get the enemy in range with highest distance traveled and shoot a bullet in that direction:
    private int range = 100;
    
    public void act()
    {
        //if it can shoot (add timer so it doesn’t fire constantly)
        {
            int mostDistanceTraveled = 0;
            Enemy target = null;
            for (Enemy e: getObjectsInRange(range, Enemy.class))
            {
                int distance = e.getDistanceTraveled();
                if (distance > mostDistanceTraveled)
                {
                    mostDistanceTraveled = distance;
                    target = e;
                }
            }
            
            if (target != null)
            {
                //maybe turning the tower in the direction of the target, too
                Bullet b = new Bullet();
                getWorld().addObject(b, getX(), getY());
                b.turnTowards(target.getX(), target.getY());
            }
        }
    }
You need to login to post a reply.