Bug with ArrayList

  • use PVector for a random point OK
  • use a ArrayList for a number of this points good,
    because you want add and remove

– the use of class did not come into my mind for this points or target-line drawing
as it is not shorter or smarter… but, why not.

i just did not understand what the second ArrayList “momPos” is for?
using the same points?

meanwhile not sure what you want to do anyhow, i try my own
test, possibly take a look

Auto Shooter
// https://discourse.processing.org/t/bug-with-arraylist/5949?u=kll
// make a arraylist of pvector points
// calc shortest distance to the next target, aim, fire, remove the point....

int idt, pmax = 10;
ArrayList<PVector> points = new ArrayList<PVector>();
PVector target = new PVector(0, 0);
boolean theend = false, shoot = false;

int k = 0;  //firing circles

void setup() {
  size( 500, 500);
  for (int i = 0; i < pmax; i++) points.add(new PVector(random(-width/2, width/2), random(-height/2, height/2)));
  for ( PVector p : points ) println(p);
}

void draw_lines() {
  stroke(200, 0, 0);
  line(target.x, -height/2, target.x, height/2); 
  line(-width/2, target.y, width/2, target.y);
}

void draw_points() {
  for (int i = 0; i < points.size(); i++) { 
    if ( i == idt ) stroke(200, 0, 0); 
    else noStroke();
    fill(0, 200, 0);
    ellipse(points.get(i).x, points.get(i).y, 8, 8);
  }
}

int get_nearest() {
  int idx = -1;
  float tdist = width;
  for (int i = 0; i < points.size(); i++) {
    float thisdist = dist(points.get(i).x, points.get(i).y, target.x, target.y);
    if ( thisdist < tdist ) { 
      tdist = thisdist; 
      idx = i;
    }
  }
  return idx;
}

void aim() {
  if ( idt > -1 ) {
    PVector waytotarget = points.get(idt).copy();
    waytotarget.sub(target);
    if ( waytotarget.mag() > 0.5 ) {
      waytotarget.setMag(waytotarget.mag()*0.01);              // calc faster to short step in that direction
      target = target.add(waytotarget);     // change target
    } else { 
      if ( !shoot ) println("shoot at "+idt);       // only print 
      shoot = true;
      points.remove(idt);
    }
  } else { 
    println(" i win ! "); 
    theend = true;
  }
}

void fire() {
  if ( shoot) {
    fill(200, 100, 0);
    ellipse(target.x, target.y, 2*k, 2*k);
    k++;
    if ( k >= 30 ) {  
      shoot = false; 
      k = 0;
    }
  }
}

void show_end() {
  fill(0, 200, 0);
  rect(-50, -25, 100, 40);
  fill(200, 0, 0);
  text(" I WIN ! ", -20, 0);
}

void draw() {
  background(200, 200, 0);
  translate(width/2, height/2);
  if ( !theend ) {
    idt = get_nearest();
    draw_lines();
    draw_points();
    if ( !shoot ) aim();              // not walk while firing
    fire();
  } else show_end();
}

if i am OFF, just ignore it.