Random position for blocks without overlaping

Hi all,

I am a newborn in this world of programming so I will appreciate your comments. I am trying to create blocks with a random x position but the same y position. The thing is that I don't want them to overlap. The blocks will produce a sound when clicking on them but just forget about those parameters now-SineWave, Position, etc. I appreciate the comments about the position of the blocks.

int unit = 7;
boolean isOn = true;
int i;
int space = 10;
int width = 1000;
int height= 1000;
int wideCount = width / unit;


Block[] block = new Block[unit];


void setup() {
  size(width, height);
  background(25);  

  for (i=0; i<unit; i++) {
     block[i] = new Block(int(random(1, 1000)),100, i, block, "jenny"); 
     block[i].collide();
     block[i].display();
  }  

}

void draw() {
  background(25);
  for (i=0; i<unit; i++) {
    block[i].collide();
    block[i].display();
  }

}

class Block {
  int x;
  int y;
  int width = wideCount-(3*space);
  Block[] others;
  int id;
  String name;
  boolean weAreMoving = false;
  boolean display = true;


  Block(int xTemp , int yTemp, int idTemp, Block [] othersTemp, String nameTemp) {
    x = xTemp;
    y = yTemp;
    id = idTemp;
    others=othersTemp;
    name = nameTemp;
  }

   void collide(){
    for (int i = id+1; i < unit; i++){
  float distance = dist(x, y, others[i].x, others[i].y);
  float minDist = others[i].width/2 + width/2; 
  if (distance < minDist){
    display = false;
    break;
  }
    }
   }

   void display(){
     if(!display) return;
     stroke(255,0,0); 
     fill(255); 
     rect(x, y, width, 100);
     println(width);
   }
}
Tagged:

Answers

  • You'll have better luck if you get rid of anything not directly related to your problem- if you aren't asking about minim, then remove anything that has to do with minim. Make it so we can copy and paste your program into our own editors to run it.

    Also, you can format your code by highlighting it and pressing the code button (it looks like a C).

    There are any number of ways to accomplish this: you might use a grid, or simply detect when a placed block intersects another one and place it somewhere else, or generate the locations procedurally. Which approach you take really depends on your own personal style of coding.

  • Answer ✓

    ??

    in line 68 you say the rects width be width

    shouldn't that be 60?

    Also, then you don't need an overlap check

    just make a random that is

    xNew = random (the pos of the last + its width , 
             the pos of the last + its width + new width); 
    
Sign In or Register to comment.