[gameprogrammer] Constraining a line to a rectangle

  • From: "Kevin Jenkins" <gameprogrammer@xxxxxxxxxx>
  • To: <gameprogrammer@xxxxxxxxxxxxx>
  • Date: Mon, 12 Apr 2004 21:35:40 -0700

In my game I have a series of lines.  For each line, it is possible that one
or both of the endpoints is outside the viewport, which is smaller than the
screen.  Given the endpoints of the line, I want to modify these endpoints
so I when I render a line between the two endpoints, all rendering is done
inside the viewport.

I want to write a function that takes the following parameters:
Point A by reference.  As input, one of the endpoints of the line.  As
output, the modified endpoint.
Point B by reference.  As input, one of the endpoints of the line.  As
output, the modified endpoint.
Viewport upper left coordinate
Viewport lower right coordinate.

The function should modify point A and point B such that when a line is
drawn from A to B, the line is only drawn within the viewport.

My initial thought as to the solution is to solve for line intersection for
each of the 4 edges of the viewport.  If the line intersects the edge of the
viewport, then set the endpoint of the line at that point.  Of course there
are still annoying issues, such as that I don't know whether to set Point A
or Point B to the point of intersection.

While I can brute force it, I think there must be a much simpler and more
elegant solution.

Ideas?


Other related posts: