This site requires JavaScript, please enable it in your browser!
Greenfoot back
cxcpio
cxcpio wrote ...

2020/11/14

Avoiding overlapping objects

cxcpio cxcpio

2020/11/14

#
I am trying to add several objects to my world at random but want to make sure none of them overlap.
//in double for loop
addObject(new square(),offsetX,offsetY);
isEmpty[x][y]=true;
//getting the random starting points
startX=rand.nextInt(size);
startY=rand.nextInt(size);
Actor carrier1= new carrier1();
carrier1.turn(rotation);
addObject(carrier1, startXcoordinatescarrier, startYcoordinatescarrier);
isEmpty[startXcarrier][startYcarrier]=false;
if (isEmpty[startXbattleship][startbattleship]==true)
{
  Actor battleship1= new battleship1();
  battleship1.turn(rotation);
  addObject(battleship1, startXcoordinatesbattleship, startYcoordinatesbattleship);
  isEmpty[startXbattleship][startYbattleship]=false;
}
With the last if statement, I would expect it to make sure that the location is empty however I sometimes experience them overlapping..
Super_Hippo Super_Hippo

2020/11/14

#
Maybe you can add it, and after adding it (addedToWorld-method), check if it intersects with any other one and if it does, immediately find a new location and check again.
danpost danpost

2020/11/14

#
cxcpio wrote...
//getting the random starting points
This makes it appear your objects can span more than one grid square; yet, you only set exactly one square as not empty when you place an object. You need to set all squares an object covers as not empty for your code to work. Also, you need check all square an actor will cover to place that actor -- not just the one where it starts at.
You need to login to post a reply.