I'm trying to create random items in a libgdx project.I'm relatively new to Java,but here is the code I've come up with for the method. I've been at this for a week now,and figured I'd ask here for an answer. I've been trying to come up with something that works first.So please do forgive the shabby code. The number parameter of the method is the number of items that will be created. The item just needs to have a random x positon,which is generated within the constraints of the width of the container. The game is as bottom up scroller,with different platforms being generated.
private Item[] generateRandomItems(int number){
Money[] items=new Money[number];
for(int i=0;i<number;i++){
Random r=new Random();
int x =r.nextInt(120)+3;//136 is the width of the container to which the item is to be generated
Money tempitem=generateMoney(x);//generateMoney() just returns a new instance of the Money class with the created x passed in as a param.
if(i!=0) {
for (int j=0;j<i;j++) {
boolean failed=true;
while (failed) {
//getItem() returns the bounding rectangle/circle f the item
if (!Intersector.overlaps(tempitem.getItem(), items[j].getItem())) {
failed = false;
items[i] = tempitem;
}else{
Random random= new Random();
int newX=random.nextInt(120)+3;
tempitem=generateMoney(newX);
}
}
}
}else{
items[i]=tempitem;
}
}
return items;
}
I don't know if this is a correct way to do it or not,but the created Items do collide sometimes.I've been trying to find what's wrong with the code for sometime now.Any suggestions to improve the code are also appreciated.
Edit::I Know that the code is unnecessarily complicated.This is my first attempt at procedural generation.So please do forgive me.
Thanks for the answers.I now know that checking each generated item for collision without saving the previously generated item is bad. But I got the previous code working after some help,and wanted to share it with anyone who would need it in the future. I moved the checking part into a new method,and added a new flag to see if the item was generated correctly,after checking for collision from all the items before it.