6
\$\begingroup\$

In my game, I want to generate randomize enemies inside of this green area that I made with a custom editor tool. enter image description here

enter image description here

\$\endgroup\$
  • \$\begingroup\$ I notice that in your example image showing generation points inside your polygon, all of the candidate points appear to be clamped to integer coordinates (grid intersections). Is this representative of the output you want, or do you want the generator to also produce points inside the grid squares? \$\endgroup\$ – DMGregory Dec 24 '16 at 18:30
  • \$\begingroup\$ I want the generator to also produce points inside the green area I know about integer coordinates.generation in circle isn't my target but I have problem in it.I ask two question 1.how can I generate enemies in green area 2.how can I generate objects in circle without Random.insideUnitCircle. main question is 1 but I like have two answer what am I doing? should I remove my second question? \$\endgroup\$ – Seyed Morteza Kamali Dec 24 '16 at 18:36
  • 1
    \$\begingroup\$ Your second question, about generating points inside a disc, already has an answer here. I'm curious why you'd want to roll your own implementation of this though when Unity already provides a simple method to do it. \$\endgroup\$ – DMGregory Dec 24 '16 at 18:42
6
\$\begingroup\$
  1. Triangulate the area.
  2. Pick a random triangle.
  3. Generate a random point inside that triangle (link).
| improve this answer | |
\$\endgroup\$
  • 3
    \$\begingroup\$ I think this is the most robust method. Just note that you need to use a weighted random selection when choosing a triangle in step 2, assigning each triangle a weight proportional to its area. That way large triangles won't be under-sampled, or small triangles over-sampled, relative to their share of the total shape. You can use the Alias method to speed up the generation of many random samples from a weighted list. \$\endgroup\$ – DMGregory Dec 24 '16 at 18:20
3
\$\begingroup\$

This might not be the most elegant solution, but it might work for you:

Drawback: Should the polygon for some reason have an area of zero, you will run into an infinite loop. It can even become a performance bottleneck when the area is just very small compared to the area of the bounding box. You can mitigate that problem by limiting the maximum number of tries, but then you no longer have a guarantee that every spawn will be successful.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.