Skip to content

Instantly share code, notes, and snippets.

@betzerra
Created May 27, 2012 21:19
Show Gist options
  • Save betzerra/2815942 to your computer and use it in GitHub Desktop.
Save betzerra/2815942 to your computer and use it in GitHub Desktop.
Detect a point in a triangle in Cocos2d
// found in http://www.cocos2d-iphone.org/forum/topic/9138
CGFloat GBDot(const CGPoint v1, const CGPoint v2) {
return v1.x*v2.x + v1.y*v2.y;
}
CGPoint GBSub(const CGPoint v1, const CGPoint v2) {
return CGPointMake(v1.x - v2.x, v1.y - v2.y);
}
BOOL GBPointInTriangle( CGPoint point, CGPoint pointA, CGPoint pointB, CGPoint pointC ) {
//http://www.blackpawn.com/texts/pointinpoly/default.html
CGPoint v0 = GBSub(pointC, pointA);
CGPoint v1 = GBSub(pointB, pointA);
CGPoint v2 = GBSub(point, pointA);
// Compute dot products
CGFloat dot00 = GBDot(v0, v0);
CGFloat dot01 = GBDot(v0, v1);
CGFloat dot02 = GBDot(v0, v2);
CGFloat dot11 = GBDot(v1, v1);
CGFloat dot12 = GBDot(v1, v2);
// Compute barycentric coordinates
CGFloat invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
CGFloat u = (dot11 * dot02 - dot01 * dot12) * invDenom;
CGFloat v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u > 0) && (v > 0) && (u + v < 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment