# Check point in triangle test

## Recommended Posts

simotix    142
In order to not clutter up other topic I thought I would separate this. Basically I am trying to do a 3d point in triangle test but I am getting a false positive. I have the point (p, (1.5, 2.0, 0)) that I want to test against a triangle, which is built clockwise with the verticies v1(4, 0, 4), v2(4, 0, 0) and v3(0, 0, 0). I was reading the algorithm in http://www.blackpawn.com/texts/pointinpoly/default.html . Basically right away you could tell by just looking at the points that the point is not in the triangle because it is not on the same place. In the following code I do not do a point in plane collision check because the way I read the algorithm the cross product (from same side) does not make this necessary. Could someone take a look at the code and see what I may be doing wrong?
D3DXVECTOR3 vTestPoint(1.5f, 2.0f, 0.0f);
D3DXVECTOR3 v1(4.0f, 0.0f, 4.0f);
D3DXVECTOR3 v2(4.0f, 0.0f, 0.0f);
D3DXVECTOR3 v4(0.0f, 0.0f, 0.0f);

bool sameSide(const D3DXVECTOR3& p1, const D3DXVECTOR3& p2, const D3DXVECTOR3& a, const D3DXVECTOR3& b)
{
D3DXVECTOR3 cp1, cp2;
D3DXVec3Cross(&cp1, &(b-a), &(p1-a));
D3DXVec3Cross(&cp2, &(b-a), &(p2-a));

if(D3DXVec3Dot(&cp1, &cp2) >= 0)
return true;

return false;
}

bool checkPointInTriangle(const D3DXVECTOR3& point, const D3DXVECTOR3& pa,const D3DXVECTOR3& pb, const D3DXVECTOR3& pc)
{
if(sameSide(point, pa, pb, pc) && sameSide(point, pb, pa, pc) && sameSide(point, pc, pa, pb))
return true;

return false;
}



##### Share on other sites
CodeMunkie    805
Haven't dug in too deep, but shouldn't it be:

if(sameSide(point, pa, pb, pc) && sameSide(point, pb, pc, pa) && sameSide(point, pc, pa, pb))		return true;

It looks you are reversing the winding order in that second test.

##### Share on other sites
simotix    142
Ah, this issue is now fixed. Thank you for the help =)

##### Share on other sites
oliii    2196
if you have no winding ordering, you have to use 'xnor' instead of 'and' :)

##### Share on other sites
simotix    142
I was thinking of different ways it could work, but I did fix the problen. Thanks for looking into it though

##### Share on other sites
grhodes_at_work    1385
This is a common question. Please refer to references contained in the Forum FAQ. You should look for questions 9 and 10 in the technical FAQ.