Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>Suppose your vector is <code>(x,y)</code>, and for the moment assume that both coordinates are positive. The slope is <code>y/x</code> and the equivalent quantity for the rectangle is <code>h/w</code>, using a coordinate system in which the rectangle's center is at <code>(0,0)</code>. Now, if <code>y/x &gt; h/w</code>, your intersection point will be on the top edge, so you know its height is h/2. You can then compute the coordinates as <code>(0.5*h*x/y,0.5*h)</code>. If <code>y/x &lt; h/w</code>, the intersection point is on the right edge, and the coordinates are <code>(0.5*w,0.5*w*y/x)</code>.</p> <p>To use this in practice, you'd want to actually do the comparison between <code>y*w</code> and <code>x*h</code>, 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 of <code>x</code> and <code>y</code>. So in code, it'd look something like this:</p> <pre><code>def intersect_perimeter(x, y, w, h): if abs(y*w) &gt; abs(x*h): return (0.5*h*x/abs(y), 0.5*h*sign(y)) else: return (0.5*w*sign(x), 0.5*w*y/abs(x)) </code></pre> <p>(untested). This will fail if <code>x</code> is zero and either <code>y</code> or <code>w</code> is 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.</p> <p>If your rectangle is centered at a point other than <code>(0,0)</code>, you just need to add the position vector representing the rectangle's center to the result from that function. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload