I’m using Python 2.7 and Pygame but any language answer will do.
I’m trying to find a given point along the vector in the perimeter of a rectangle. I know the vector, and the center, width and height of the rectangle, but the center can be (0, 0) for the sake of simplicity
So for example I want to find the point in the perimeter of the rectangle following the vector of roughly (0.7, 0.7) of a rectangle that is 2 wide by 6 height.
What I’ve got working now does the work; but there’s has got to be a better, more elegant way: I’m taking the length of the wider value between height and width of the rectangle and using every number in between that and 0 and testing that against each of the 4 sides of the rectangle and see if it’s in it.
This is the code I use specific to my game, not generalized at all: http://pastebin.com/8Ai1iQeL
I’d go about this by comparing the ratio of the components of your vector, which is also the slope of the line parallel to the vector, to the same quantity for the vector pointing from the rectangle’s center to its corner. That tells you whether the vector hits a horizontal or vertical side. After that, you can use a simple proportionality to find the intersection point.
Suppose your vector is
(x,y), and for the moment assume that both coordinates are positive. The slope isy/xand the equivalent quantity for the rectangle ish/w, using a coordinate system in which the rectangle’s center is at(0,0). Now, ify/x > h/w, your intersection point will be on the top edge, so you know its height is h/2. You can then compute the coordinates as(0.5*h*x/y,0.5*h). Ify/x < h/w, the intersection point is on the right edge, and the coordinates are(0.5*w,0.5*w*y/x).To use this in practice, you’d want to actually do the comparison between
y*wandx*h, both to avoid problems with division by zero and to avoid the relatively expensive division operator (not that that really makes much of a difference). Also, you can find the correct signs for the components of the intersection point by just using the signs ofxandy. So in code, it’d look something like this:(untested). This will fail if
xis zero and eitheryorwis zero, but in that case you have either a zero vector (and the problem is undefined) or a zero-width rectangle (again, the problem is undefined). So I wouldn’t bother with error checking for that case.If your rectangle is centered at a point other than
(0,0), you just need to add the position vector representing the rectangle’s center to the result from that function.