<?php // distance between two 2D points $x1 = 3; $y1 = 4; $x2 = 7; $y2 = 1; $dist = hypot($x2 - $x1, $y2 - $y1); // 5.0 // why not just sqrt(($dx)**2 + ($dy)**2)? // because hypot() avoids intermediate overflow // QUICK TIP STRAIGHT FROM GAME DEV: sometimes you only want to *compare* distances, and // square root is SLOW // in this case, just compare squared values, it's equivalent! $dx1 = $x2 - $x1; $dy1 = $y2 - $y1; $dist1Sq = $dx1 * $dx1 + $dy1 * $dy1; // some other points in space... $dist2Sq = $dx2 * $dx2 + $dy2 * $dy2; if ($dist1Sq < $dist2Sq) { // squared value compared, way faster without square root! echo "Point 2 is closer to Point 1\n"; } else { echo "Point 3 is closer to Point 1\n"; }
You have javascript disabled. You will not be able to edit any code.