HTML and CSS Reference
In-Depth Information
For our purposes, we want to determine the value of t when distance is at a minimum. Lessons from
calculus and reasoning about minimum versus maximum in this situation tell us first that we can use the
distance squared in place of the distance and so avoid taking square roots. Moreover, the value is at a
minimum when the derivative (with respect to t) is zero. Taking the derivative and setting that expression
to zero, produces the value of t at which the cx,cy is closest to the line. In the code, we define two extra
variables, dx and dy, to make the expressions simpler.
dx = fx-sx
dy = fy-sy ;
t= 0.0 -((sx-cx)*dx+(xy-cy)*dy)/((dx*dx)+(dy*dy))
This will produce a value for t. The 0.0 is used to force the calculations to be done as floating point
numbers (numbers with fractional parts, not restricted to whole numbers).
We use equations a and b to get the x,y point corresponding to the value of t. This is the x,y closest to
cx,cy. If the value of t is less than 0, we check the value for t = 0, and if it is more than 1, we check the
value for t = 1. This means that the closest point was not a point on the line segment, so we will check the
appropriate end of the line segment closest to that point.
Is the distance from cx,cy to the closest point close enough to be called a collision? We again use
distance squared and not distance. We evaluate the distance squared from cx, cy to the computed x,y. If
it is less than the radius squared, there is an intersection of the circle with the line segment. If not, there is
no intersection. Using the distance squared does not make a difference: if there is a minimum for the value
squared, then there is a minimum for the value.
Now the very good news here is that most of the equations are not part of the coding. I did the work
beforehand of determining the expression for the derivative. The intersect function follows, with
comments:
function intersect(sx,sy,fx,fy,cx,cy,rad) {
var dx;
var dy;
var t;
var rt;
dx = fx-sx;
dy = fy-sy;
t =0.0-((sx-cx)*dx+(sy-cy)*dy)/((dx*dx)+(dy*dy)); //closest t
if (t<0.0) { //closest beyond the line segment at the start
t=0.0; }
else if (t>1.0) { //closest beyond the line segment at the end
t = 1.0;
}
dx = (sx+t*(fx-sx))-cx; // use t to define an x coordinate
dy = (sy +t*(fy-sy))-cy; // use t to define a y coordinate
rt = (dx*dx) +(dy*dy); //distance squared
if (rt<(rad*rad)) { // closer than radius squared?
return true; } // intersect
else {
Search WWH ::




Custom Search