Collision with Triangles
Posted: Sat Jul 07, 2007 2:59 am
Hi everybody!
I'm trying to make an algorithm that determines wether a point is inside a triangle. So far I've done this:
But as you can see it doesn't work near the bottom of it (I'm almost sure the other two sides won't work in some other cases...). Well, if someone out there could help me I would really appreciate! 
I'm trying to make an algorithm that determines wether a point is inside a triangle. So far I've done this:
Code: Select all
initmouse()
initsprite()
OpenWindow(1,0,0,640,480,#PB_Window_ScreenCentered,"triangle collision")
OpenWindowedScreen(WindowID(1),0,0,640,480,0,0,0)
structure T_point
x.f
y.f
endstructure
structure T_triangle
relative.T_point
p.T_point[3]
endstructure
procedure make_triangle(*t.T_triangle,x1.f,y1.f,x2.f,y2.f,x3.f,y3.f)
*t\p[0]\x=x1
*t\p[0]\y=y1
*t\p[1]\x=x2
*t\p[1]\y=y2
*t\p[2]\x=x3
*t\p[2]\y=y3
endprocedure
procedure triangle_collision(*t.T_triangle,mx.f,my.f)
mx-*t\relative\x
my-*t\relative\y
;verify if its on the first side area
rx.f=(*t\p[1]\x-*t\p[0]\x)
ry.f=(*t\p[0]\y-*t\p[1]\y)
if mx*ry+my*rx=>rx*ry
rx.f=(*t\p[2]\x-*t\p[1]\x)
ry.f=(*t\p[1]\y-*t\p[2]\y)
if mx*ry+my*rx=>rx*ry
rx.f=(*t\p[0]\x-*t\p[2]\x)
ry.f=(*t\p[2]\y-*t\p[0]\y)
if mx*ry+my*rx=>rx*ry
procedurereturn 1
else
procedurereturn 0
endif
else
procedurereturn 0
endif
else
procedurereturn 0
endif
endprocedure
createsprite(0,128,128)
createsprite(2,128,128)
createsprite(1,5,5)
tri.T_triangle
make_triangle(tri,0,78,64,0,128,128)
tri\relative\x=120
tri\relative\y=120
startdrawing(spriteoutput(0))
frontcolor(0,0,255)
linexy(tri\p[0]\x,tri\p[0]\y,tri\p[1]\x,tri\p[1]\y)
linexy(tri\p[1]\x,tri\p[1]\y,tri\p[2]\x,tri\p[2]\y)
linexy(tri\p[2]\x,tri\p[2]\y,tri\p[0]\x,tri\p[0]\y)
stopdrawing()
startdrawing(spriteoutput(2))
frontcolor(0,0,255)
linexy(tri\p[0]\x,tri\p[0]\y,tri\p[1]\x,tri\p[1]\y)
linexy(tri\p[1]\x,tri\p[1]\y,tri\p[2]\x,tri\p[2]\y)
linexy(tri\p[2]\x,tri\p[2]\y,tri\p[0]\x,tri\p[0]\y)
fillarea(64,64,rgb(0,0,255),rgb(128,128,255))
stopdrawing()
startdrawing(spriteoutput(1))
frontcolor(255,0,0)
box(0,0,5,5)
stopdrawing()
repeat
clearscreen(0,0,0)
if triangle_collision(tri,mousex(),mousey())
displaysprite(2,120,120)
else
displaysprite(0,120,120)
endif
displaysprite(1,mousex(),mousey())
flipbuffers()
examinemouse()
until mousebutton(1)