1
\$\begingroup\$

So I have a sprite of an ellipse ( it is a 2D game). I would like to get a point inside this ellipse so I can instantiate something. How would I do that? Sprite won’t be changing the scale, so uniform scale.

The point shouldn’t be on the edge and a bit further away from the edge

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This question has been asked there stackoverflow.com/questions/5529148/… \$\endgroup\$
    – Alexis
    Feb 22, 2019 at 9:15
  • \$\begingroup\$ Note that the top answer, though not accepted, does solve the problem and give a uniform distribution. I also double checked it numerically. \$\endgroup\$
    – Alexis
    Feb 22, 2019 at 9:43

1 Answer 1

1
\$\begingroup\$

If you know the width and height, then a random, non-uniform value could be obtained, by getting a random angle and a random value between 0 and 1. 1 means the point is at the edge, 0 is at the center. These can be converted into an XY coordinate system using

$$angle = rand() * 2 * \pi$$ $$\lambda = rand()$$ $$x=\frac{cos(angle)\cdot width}{2}\cdot \lambda$$ $$y=\frac{sin(angle)\cdot height}{2}\cdot \lambda$$

Where \$rand()\$ returns a random value between 0 and 1.

The problem with this is that i tends to generate more points in the center, since there's less space there.

To solve this, you could instead try to generate a random point in the rectangle that contains the ellipse, check if it's inside the ellipse, if it isn't, try again. It's easy to check if a point lies inside an ellipse. If the point is \$(x,y)\$, then

$$d = \sqrt{(2x/width)^2+(2y/height)^2}$$

If \$d\$ is less than or equal to 1, it's inside

\$\endgroup\$
5
  • \$\begingroup\$ How would you get the height and width of the ellipse? \$\endgroup\$
    – user122760
    Feb 22, 2019 at 9:38
  • 2
    \$\begingroup\$ @user122760 You created that ellipse, how do you not know the height and width? \$\endgroup\$
    – Bálint
    Feb 22, 2019 at 9:51
  • \$\begingroup\$ I actually used one online \$\endgroup\$
    – user122760
    Feb 22, 2019 at 14:26
  • \$\begingroup\$ @user122760 Measure it somehow. If you don't know anything about an ellipse, you can check if a point's inside \$\endgroup\$
    – Bálint
    Feb 22, 2019 at 15:10
  • 1
    \$\begingroup\$ You can more easily solve the uniformity problem by taking the square root of lambda. This pushes values close to zero outward and exactly compensates for the bunching you'd have otherwise. \$\endgroup\$
    – DMGregory
    Mar 24, 2019 at 11:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .