samedi 2 juillet 2016

How to generate random points outside a rectangle?

Let's say my window's dimensions are 400 width by 600 height.

It's relatively easy to generate a random point on a single side, let's say the top of it:

random.randint(0, width)

But what would be the smartest way to get this to work for all 4 sides so that a random point is generated outside a rectangle?

If I do

pos_x = [random.randint(0, width)]
pos_y = [random.randint(0, height)]

They will only show up on the corners, which makes sense. The only way I can think of is to randomly create a point inside the rectangle, compare what axis is closest to a border, then clamp it. Thing is I don't know how to do this elegantly without doing 4 checks for each side (which feels redundant). I feel like there is an easier solution for this?




Aucun commentaire:

Enregistrer un commentaire