How to avoid object overlapping and overtaking?

Viewed 93

I am trying to draw circles from same y coordinate. and creating arrays for xPos. I put the speed and xPos random, how to make sure they are not overlapping and the one behind it match the speed to the front one so it wouldn't overtake?

I have retried the code, but it still overlapping for some reason that I couldn't find out? OK now I initialise the k with i+1, so whichever behind it. and I ran flow chart as well, the logic looks alright, still not doing what it should being doing.enter image description here

int Num=10;
float dia=50;
float[] xPos= new float[Num];
float[] xSpeed=new float[Num];
void setup() {
  size(300, 300);
  for (int i= 0; i<xPos.length; i++) {
    xPos[i]=random(-dia*Num);
    xSpeed[i]=3;
    boolean overlapping=false;
    for(int k=;k<xPos.length;k++){
       float newPos=xPos[k];
      float dist=(newPos-xPos[i]);
      if(dist<dia+50){
        overlapping=true;
        break;
      }
    }   
    if(!overlapping){
     draw();
    }
    }
  }
  

void draw() {
  background(255);
  drawBall();
  moveBall();
  reset();
}
void drawBall() {
  for (int i= 0; i<xPos.length; i++) {
    circle(xPos[i], 50, 50);
  }
}
void moveBall() {
  for (int i= 0; i<xPos.length; i++) {
    xPos[i]+=xSpeed[i];
  }
}
void reset() {
  for (int i= 0; i<xPos.length; i++) {
    if (xPos[i]>width) {
      xPos[i]=0;
    }
  }
}
1 Answers
  1. how to make sure they are not overlapping

For this, you could naively check if the new position has already been taken by another such as follows (I haven't run the code, so i probably has bugs, think of it more as a pseudocode):

boolean isItTaken(float[] xPos, float newPos) {
  for (int i= 0; i<xPos.length; i++) {
    if (abs(newPos - xPos[i]) < circleSize) return true;
  }

  return false;
}

for (int i= 0; i<xPos.length; i++) {
  float newPos = random(-50);
  while (isItTaken(xPos, newPos)) {
     newPos = random(-50);
  }
}

I'm sure there are better methods though. Also I think using ArrayList is better than using a simple array.

  1. and the one behind it match the speed to the front one so it wouldn't overtake?

You could set it as a constant number? If you want it to be random, but slower than the previous one, you could set the upper limit of the random function to be the speed of the previous one such as(again, probably buggy):

ArrayList<Float> xSpeed = new ArrayList<Float>;


for (int i= 0; i < Num; i++) {
  xSpeed.push(random(2, xSpeed.get(xSpeed.length - 1)));
}
Related