Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Returns the distance of the intersection point from the ray's origin.
- // Negative results mean no intersection.
- // Fails when the origin is contained in the rectangle, test for that separately, if needed.
- float intersect(Ray ray, Box box) {
- Vector2D verts[5]; // array to store the vertices of the box. verts[5] = verts[1] to make things easier
- box.getVerts(verts);
- float sin_phi = sinf(-ray.dir);
- float cos_phi = cosf(-ray.dir);
- // Rotate everything so the ray is aligned with the y-axis, its x-coord is zero
- ray.orig.rotateM(sin_phi,cos_phi);
- float xshift = -ray.orig.r[0]; // we'll skip shifting the ray itself, x is zero, y is unaffected anyway
- for (int i=0; i<4; ++i) {
- verts[i].rotateM(sin_phi,cos_phi);
- verts[i].r[0] += xshift;
- }
- verts[4] = verts[0]; // makes the next loop simpler
- for (int i=0; i<4; ++i) {
- if ((verts[i].x() < 0) && (verts[i+1].x() >= 0)) { // intersection
- Vector2D diff = verts[i+1] - verts[i];
- return verts[i].y() - diff.y()/diff.x() * verts[i].x() - ray.orig.y();
- }
- }
- // Why the above if() works:
- // - the ray's direction vector is (0,1), so the sides facing the ray have a normal vector with n.y < 0
- // - the vertices are in CCW order, so the normal of an edge will be (d.y,-d.x), where d = v[i+1] - v[i]
- // - substituting into n.y < 0 we get v[i].x - v[i+1].x < 0, which is v[i].x < v[i+1].x
- // - thus, we are only interested in the edges going left to right, so we needn't test for the opposite case
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement