Skip to main content
GameDev.net gamedev.net
🔒 Locked

[java] Circle Problem

Started by ace84_84 Oct 24, 2005 at 10:51 PM 7 replies 350+ views
Original Post
ace84_84
ace84_84
I Have created an oval (200, 200, 100, 100). does anyone know the formula, to figure out if the user's click was inside the circle?
H_o_p_s
H_o_p_s
myOval.contains(clicked_x, clicked_y);

If you were to look at the Java API for shape you would be able to see all of its funtionality.
BRING BACK THE BLACK (or at least something darker)
Kevinator
Kevinator
There's probably an easier and/or more efficient way to do it, but this is the most intuitive way to do it for me (if you want to do it explicitly):

Point center=new Point(oval.getX()+oval.getWidth()/2,oval.getY()+oval.getHeight()/2);int radius=oval.getWidth()/2;Point mouseClick=getMouseClickedCoords();/*distance formula*/int distanceFromCenter=Math.sqrt(Math.pow(center.getX()-mouseClick.getX(),2)+Math.pow(center.getY()-mouseClick.getY(),2));if(distanceFromCenter<=radius)    //inside the circleelse    //outside the circle
Nomad010
Nomad010
If you're looking for efficiency then forget the squareroot and square the radius.

IE: Instead of this: int distance = Math.sqrt(x*x + y*y)
Try this: distanceSquared = x*x + y*y

Test it against the radius squared. Though I don't think Kevinator's approach will work. It looks more suited to a circle.
"..."
Kevinator
Kevinator
Right, that's just for a circle, but then again the OP's shape is a circle. And I should be using doubles instead of ints. Good tip about omitting the sqrt method.
capn_midnight
capn_midnight
the absolute easiest way to tell if you clicked inside of a certain object, no matter the shape of the object, wether it be in 2D or 3D, with pixel perfect accuracy, is to render the scene twice: once as normal and once to an off screen buffer that is never displayed. For this second buffer, you render each object with a single color unique to that object. Then, you retrieve the pixel color from the second buffer from where you clicked. From there, since the colors are unique to each object, you'll know what object you clicked.

The easiest way to select the colors is to just use the index of the object in your pick list plus one as that color. Adding one makes sure the first object isn't rendered as black, which will be your background color.
Marianne
Marianne
that one is great if you do 3d or complex shapes, but honestly just for a circle i guess it's way too much overhead

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.