Random position without overlapping

Hi, i tried your way, it work but i have a bug, it never stop trying to place the objects. Its like the loop never stop.

here is my Class, did you see whats i do wrong ?

public class Grass2 {
	PApplet parent;
	public PVector position;
	
	int  w, h;
	float x,y;
	
	ArrayList<Grass2> grass2 = new ArrayList<Grass2>();
	int many = 10;
	boolean avoidCollide = true;
	
	
	public Grass2(float x,float y,int w,int h, PApplet p){
		this.x=x;
	    this.y=y;
	    this.w=w;
	    this.h=h;
	    parent = p;
	}
	
	
	void randomSet(){
		w = 32;
		h = 32;
		x = parent.random(250, 1750);
		y = parent.random(250, 1750);
	}
	
	public void makeGrass(){
		grass2 = new ArrayList<Grass2>();
		for(int i = 0; i < many; i++){
			randomSet();
			if(avoidCollide) while(collide(x,y,w,h)) randomSet();
			grass2.add(new Grass2(x,y,w,h,parent));
		}
	}
	
	boolean collide(float g1x, float g1y, float g1w, float g1h){
		if(grass2.size() > 0){
			for(Grass2 onegrass : grass2){
				if(g1x + g1w >= onegrass.x && g1x <= onegrass.x + onegrass.w && g1y + g1h >= onegrass.y && g1y <= onegrass.y + onegrass.h){
					return true;
				}
			}
		}
		return false;
	}
	
	public void draw(){
		parent.fill(0);
		parent.ellipse(x, y, w, h);
	}
	
	public void showGrass2(){
		for(Grass2 onegrass : grass2) onegrass.draw();
	}
}
1 Like