How can I make only one object follow a certain object in an array without it making many objects ?

Hello, I am making a Tower Defense game trying to improve my programming but I am stuck on something that has been bugging me for over a week. Basically I want the turrets that I put down to shoot at the minions that come into there range, and if it is just one minion my code works perfectly, however when two minions come into range, the turret shoots up to twice as fast, and three times faster when their is three minions in it's range. I can sort of see why it does this, but can't fully see where the error is. Here is the method I am using. cc.posX and cc.posY are the minions x and y positions. Cheers guys.

void EndOfPath() {

  for (int t = 0; t < AllTowers.size(); t++) {
    Tower tt = AllTowers.get(t);
    for (int c = 0; c < AllCreeps.size(); c++) {
      Creep cc = AllCreeps.get(c);

      if (dist(tt.TowerPosition().x, tt.TowerPosition().y, cc.posX, cc.posY) <300) {
        stroke(255, 0, 0);
        PVector locT = new PVector(tt.TowerPosition().x, tt.TowerPosition().y);
        PVector locC = new PVector(cc.posX, cc.posY);
        float x = bezierPoint(locT.x + (CellSize/2), locT.x+ (CellSize/2), locT.x+ (CellSize/2), locC.x+ (CellSize/2), r);
        float y = bezierPoint(locT.y+ (CellSize/2), locT.y+ (CellSize/2), locT.y+ (CellSize/2), locC.y+ (CellSize/2), r);
        ellipse(x, y, 10, 10);
        stroke(255, 0, 0);

        r+= 0.01;
        if (r>1.0) {

I also don't know how to use this website very well as I am a new member, if someone could aslo tell me how I can put my code in properly when asking questions, that would be great too, thanks.



  • Your code is doing exactly what you're telling it to do: you're looping over all of the creeps, checking whether each one is in the tower's range, and then firing.

    Instead, you want to only fire on the closest one (or whatever logic you use for selecting a target). Here's how to do that:

    Step 1: Use two variables: one to keep track of the closest creep, and another to keep track of the distance to that creep. Start the distance variable out at a really high value.

    Step 2: Loop over every creep. For each creep, if the distance to that creep is less than the closest distance you've found, then that creep is your new closest creep, and that distance is your new closest distance.

    Step 3: After the loop exits, that variable will hold the closest creep, which you can shoot at.

    Shameless self-promotion: I have an example of this type of loop available here.

  • to better post your code:

    leave 1 empty line before and after the code section

    select the code section

    hit ctrl-o

  • duplicate thread removed. please don't post duplicates.

This discussion has been closed.