Gamedev-Maths
Gamedev-Maths copied to clipboard
Point in a triangle problem
Using the method described in the video, when Ay and Cy are equal, the denominator becomes 0. This means that it can't be used for triangles where the the bottom line is parallel to the X axis. Is there any solution?
if(A.y===C.y){ C.y+=0.001;} the math its different
For some reason, this solution of adding an offset did not work for me. I didn't want to add 0.001 since this would introduce errors in my simulation.
Instead, I check to see if A.y and C.y are equal, and if so, I swap point A with point B.
Python test code:
import numpy as np
from matplotlib.patches import Polygon
xBounds = [0, 1000]
yBounds = [0, 800]
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def coords(self):
return [self.x,self.y]
B = point(600.0,800.0)
A = point(700.0, 450.0)
C = point(275.0,450.0)
A.coords()
pts = np.array([A.coords(), B.coords(), C.coords()])
p = Polygon(pts, closed=True, fill=False, color='b')
ax = plt.gca()
ax.add_patch(p)
ax.set_xlim(xBounds)
ax.set_ylim(yBounds)
def inTriangle(a,b,c,p):
if a.y == c.y:
a, b = b, a # do this to prevent 12 denominator being 0 !
ca_dy = c.y-a.y
ca_dx = c.x-a.x
ba_dy = b.y-a.y
ba_dx = b.x-a.x
pa_dy = p.y-a.y
w1 = (a.x*ca_dy + ca_dx*pa_dy - p.x*ca_dy)/(ca_dx*ba_dy - ca_dy*ba_dx)
w2 = (pa_dy - ba_dy*w1)/ca_dy
# print(f"{w1>=0 and w2>=0 and (w1+w2 <=1)}, {p.x:>5.1f}, {p.y:>5.1f}, {w1:.3f}, {w2:.3f}")
return w1>=0 and w2>=0 and (w1+w2 <=1)
for i in range(100):
x=np.random.uniform(low=xBounds[0],high=xBounds[1],size=1)[0]
y=np.random.uniform(low=yBounds[0],high=yBounds[1],size=1)[0]
P = point(x,y)
if inTriangle(A,B,C,P):
c = "xb"
else:
c = "xr"
ax.plot(x,y,c)
plt.show()```