Created
November 29, 2013 05:55
-
-
Save yoshiki/7702066 to your computer and use it in GitHub Desktop.
2つの線の交点座標を求める関数。 線分が交わっていないとCGPointZeroが返る。
もし線分関係なしに延長線上に交点があるのかを求める場合は7〜10行目をコメントアウトすればよい。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (CGPoint)intersectionOfLineFrom:(CGPoint)p1 to:(CGPoint)p2 withLineFrom:(CGPoint)p3 to:(CGPoint)p4 { | |
CGFloat d = (p2.x - p1.x)*(p4.y - p3.y) - (p2.y - p1.y)*(p4.x - p3.x); | |
if (d == 0) | |
return CGPointZero; // parallel lines | |
CGFloat u = ((p3.x - p1.x)*(p4.y - p3.y) - (p3.y - p1.y)*(p4.x - p3.x))/d; | |
CGFloat v = ((p3.x - p1.x)*(p2.y - p1.y) - (p3.y - p1.y)*(p2.x - p1.x))/d; | |
if (u < 0.0 || u > 1.0) | |
return CGPointZero; // intersection point not between p1 and p2 | |
if (v < 0.0 || v > 1.0) | |
return CGPointZero; // intersection point not between p3 and p4 | |
CGPoint intersection; | |
intersection.x = p1.x + u * (p2.x - p1.x); | |
intersection.y = p1.y + u * (p2.y - p1.y); | |
return intersection; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment