How to check if a point (int - Coordinates) is within the hypotenuse of a triangle
I've got a right triangle and I want to check if a given point is on the Hypotenuse of that triangle. All points are plain integers, not floating-point variables.
(broken image, original location https://tape.bplaced.net/dl/example2.png
)
Edit: All green squares would be on the hypotenuse, the white squares not. I know x, y, the Coordinates of the Corners and the Coordinates of the Point I want to test. All Coordinates are whole numbers (y is a little bit off in the 开发者_JS百科drawing, sorry).
This could work:
You know the triangle, so just create the function for the hypothenuse, in your example it would be y = 5x/12
. If you now get a point, say x = 6, y = 3
, you can use these variables to see if it comes out right: 3 = roundup(5*6/12)
. If it does, the point is on the triangle, if not - then not.
There are two cases to handle: one where the hypotenuse is vertical and the other where it is not.
For the vertical case, you just check if the point in question has a y value in the range of the hypotenuse.
For the non-vertical case, derive the equation of the hypotenuse using its endpoints. The equation of a line is y = mx + b where m is the slope which is dx/dy. Then b = y - mx.
Now that you have m and b, see if a candidate point's x and y satisfy the equation (does the point's y equal m * x + b ?).
However, practically, you should check for nearness instead of exact equality so check if the point's y is within some small delta of (m * x + b).
I'll start doing this:
points = an array;
delta=y/x
acc = 0
j = 0
for (i=0;i<x;i++){
points.push(i, j)
acc+=delta
while (acc > 1){
acc-=1
j++
points.push(i,j)
}
}
And then you have all the points in the hypotenuse. There are better algorithms for drawing lines, but this could be a start.
精彩评论