public Vector3 GetCollisionPointWithViewBox(Vector3 origin, Vector3 direction) { Vector3 point = Vector3.zero; foreach (var line in viewbox) { Vector2 q = line.start; Vector2 s = line.end - line.start; Vector2 p = SMath.Vec3ToVec2(origin); Vector2 r = SMath.Vec3ToVec2(direction); // The intersection is where q + u*s == p + t*r, and 0 <= u <= 1 && 0 <= t // t = (q − p) × s / (r × s) // u = (q − p) × r / (r × s) float crossRS = SMath.CrossProduct2D(r, s); float crossQP_S = SMath.CrossProduct2D(q - p, s); float crossQP_R = SMath.CrossProduct2D(q - p, r); if (crossRS == 0) { // TODO: other situations } else { float t = crossQP_S / crossRS; float u = crossQP_R / crossRS; if (0 <= u && u <= 1 && 0 <= t) { point = q + u * s; break; } } } return(point); }