Kees Koenen
Kees Koenen

Reputation: 770

Avoiding specific ranges in canvas when placing objects randomly

I place objects on random positions on the screen (canvas) :

 public float X=Rnd.nextInt((MainGamePanel.width - 60) - 20) + 20;
 public float Y=Rnd.nextInt((MainGamePanel.height - 30) - 30) + 30;

This works fine. Now; What if I want to avoid placing objects over (40,50) - (60,80).. for instance, because I have a button there, I don't want the button to be covered with visible objects.

Ofcourse, I could implement a "checkposition" routine, that re-randomizes if the object-position is placed somewhere within the button-area. But is this the best (cleanest, neatest, fastest) solution? Thanks for your thoughts!

Upvotes: 1

Views: 168

Answers (1)

tabs
tabs

Reputation: 58

Fixed amount of time to create the objects

Create the objects in four areas, not one.

Have more than one set (x,y) of randomized numbers and split the percentage of created objects in each according to the size of each area. If you can picture four rectangles that snugly fit together outside of the button area then you have your areas. Depending on how many objects you are creating and the effect you are looking for this could work.

This could be a terrible idea though if you sometimes, randomly, want lots of objects in one part of the screen, as you are forcing the distribution. Also what if you want another button somewhere else on the screen, not adjacent to the current one? Might get a bit messy with lots of areas.

The advantage with this solution is that it takes a predictable amount of time to create all the objects. It should be the same every time.

Variable amount of time to create the objects

Use a checkPostion() method.

It's probably just easier to use a checkPostion() method and grab a new random number. If you are smart about it, you should realise that in a lot of cases you'll only need to 're-roll' one coordinate and not both.

Upvotes: 1

Related Questions