See the image above; basically, I want a simple test to check if a point is within the line segment's range. The information (or input, if you prefer) I have is the point's coordinates, and the line segment termination points' coordinates. The output I want is a simple boolean. How can I check this in a simple way?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
It's not hard to determine the equations of those perpendicular dotted lines passing through the endpoints of your bold line.
Let the bold line be defined by the points
(x1, y1)
and(x2, y2)
. Then, it has a slopeSo all perpendicular lines will be of the form
We can use that to determine the equations of the perpendicular lines that pass through
(x1, y1)
and(x2, y2)
(respectively), which essentially represent the boundary of the region in which all valid points must reside:So, for an arbitrary point
(x*, y*)
, to determine if it lies in the valid region, you can test whether(or the reverse if
ya(x*)
is larger)The following should do the trick:
You can have a simple and uniform check if you use the inner product. The inner product between two vectors can be geometrically visualised as the product of the lengths of the two vectors time the cosine of the angle between the two, or the product of the length of one of the vectors and the length of the (orthogonal) projection of the other onto the line determined by that vector.
In your situation, if you project the vector
v
from one of the endpoints of the segment to the point under consideration, the point lies inside the allowed region if and only if the projection falls on the segments
connecting the two endpoints. And that is equivalent to(strict inequalities if you want to exclude the lines perpendicular to the segment through the endpoints)
You can do this by computing the angles.
Suppose your endpoints are (x1,y1) and (x2,y2), and your point is (x,y).
Then you create two vectors, from one endpoint to other, and one endpoint to your point:
Compute the dot product:
Now the dot product divided by magnitude gives you the cosine of the angle:
Now the trick is that if your angle is greater than
PI / 2
, you are 'out'I took Daniel Fischer answer which is great, and adjusted it for 3D and Unity: