1
\$\begingroup\$

I want to calculate in java when a circle is inside an ellipse. I drew an example below:

Play field

For this particular problem, the top left corner of the field has the position 0.0f, 0.0f. The bottom right corner has the position 1.0f, 1.0f. The position of the bat is: 0.48f, 0.94f. The goal is located at: 0.5f, 1.0f, height is 0.1f and the radius 0.4f.

How can I calculate if the bat is inside the ellipse? What is the general algorithm?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Ellipse math is not significantly more difficult than circle math (for detecting distance from the center).

enter image description here

To detect if a point is inside an ellipse, you check a (a/b) ratio of each component of the coordinate against a known constant. So really, it's the same as any 2-Vector distance check, except you manipulate the coordinates slightly before squaring them.

For example, if you scale the y-coordinate to the same range as the x-coordinate, you can treat it identically to circle. Like so:

Vector2 puckPos = {puck_x, puck_y};
Vector2 goalCenter = {screen_height, screen_width / 2};

float a = 0.4f * screen_width;
float b = 0.1f * screen_height;

if ((
       (puckPos.y * (a / b) - goalCenter.y) ^ 2 + 
       (puckPos.x - goalCenter.x) ^ 2
    ) < a ^ 2) {

       // inside ellipse
}
\$\endgroup\$
5
  • \$\begingroup\$ What do you mean with: "manipulate the coordiates slightly before squaring them."? Can you maybe give an example? \$\endgroup\$
    – user35774
    Oct 4, 2013 at 14:17
  • \$\begingroup\$ To speed things along, you may also wish to keep track of a second ellipse that describes valid values for the center of the bat. \$\endgroup\$ Oct 4, 2013 at 14:18
  • \$\begingroup\$ @user35774 I added some code; tell me if that makes sense. \$\endgroup\$ Oct 4, 2013 at 15:57
  • \$\begingroup\$ if you add the h and k terms, you can do: if (((x-h)*(x-h)/a/a+(y-k)*(y-k)/b/b)<1) { /*yer in*/} else {/*yer not*/} //h and k are center x and center y respectively \$\endgroup\$ Oct 4, 2013 at 16:10
  • 1
    \$\begingroup\$ Possibly worth noting: this is correct for point-in-ellipse, but not for doing circle-in-ellipse testing (or circle-ellipse intersection testing), which is actually a substantially harder problem. \$\endgroup\$ Oct 4, 2013 at 20:17

You must log in to answer this question.

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