- Home /
Checking whether an object is within a 'shape'
Hi there, I have some basic code which tracks the player's input and stores an array of points. Taken from another post in Unity Answers, I then perform a few checks to determine whether it's 'close' in shape to a circle (at least nearly a closed loop):
I check how far the first point is from the last;
I check that there are a minimum of 4 points;
From all the points stored, I calculate the average of their x and y positions/number of points to generate a 'centre' point.
All is well, this seems to do the trick. However, what I need to achieve next is to ascertain whether an object is 'within' the shape the player has drawn (remembering that it could be a non uniform shape, so I can't rely on a consistent radius). So in the attached pic, you can see the points, the centre point and an object.
Could anyone point me in the right direction? With a circle it'd be easy, but this is a little more tricky....
This is not a Unity question, but more a CSci/General program$$anonymous$$g question. You might have more luck on StackOverflow. I had to implement this years ago, and found algorithms on the net. If I remember correctly, my implementation walked the segments seeing if the object is on the left or right of each segment. If it is on the same side for all line segments, it is inside. Note if you get complex shapes (lines over the top of each other), inside can appear strange to a user.
If you choose a point X outside the polygon, and make a line from X to Point, then you know that:
If the line crosses the polygon an odd number of times, Point is inside. Otherwise, it's outside.
I don't know the math for it, but you could brute-force the solution by comparing the line to every line segment you already have defined, and count the number of intersections.
Answer by dchen05 · Jun 19, 2013 at 12:11 AM
Perhaps I don't understand the question, but couldn't this do what you want? http://wiki.unity3d.com/index.php?title=PolyContainsPoint
Just use your shape points to define the poly.
Your answer
![](https://koobas.hobune.stream/wayback/20220613094908im_/https://answers.unity.com/themes/thub/images/avi.jpg)