Math.hypot()はJavaScriptで二点間の直線距離(ユークリッド距離)を簡単に計算できる便利な関数です。この記事では、Math.hypot()の基本的な使い方から実践的な例まで解説します。

Math.hypot()とは

Math.hypot()は、引数として与えられた数値の二乗和の平方根(平方根)を計算する関数です。主に以下の用途で使用されます:

  • 2点間の直線距離の計算
  • ベクトルの長さ(大きさ)の計算
  • 三角形の斜辺の長さの計算

基本的な使い方

// 基本的な構文
Math.hypot(x, y)
Math.hypot(x, y, z)

// 2次元での使用例
const distance = Math.hypot(3, 4);  // 5を返す

// 3次元での使用例
const distance3D = Math.hypot(3, 4, 5);  // 7.0710678118654755を返す

実践的な使用例

2点間の距離計算

// 2点のxy座標から距離を計算
const point1 = { x: 0, y: 0 };
const point2 = { x: 3, y: 4 };

const distance = Math.hypot(
  point2.x - point1.x,
  point2.y - point1.y
);

console.log(distance); // 5

ゲーム開発での活用例

// プレイヤーと敵の距離を計算
function calculateDistance(player, enemy) {
  return Math.hypot(
    enemy.x - player.x,
    enemy.y - player.y
  );
}

const player = { x: 10, y: 20 };
const enemy = { x: 13, y: 24 };

const distance = calculateDistance(player, enemy);
console.log(distance); // 5

エラー処理とよくある問題

NaN(Not a Number)の処理

// 引数が数値でない場合
console.log(Math.hypot('a', 4));  // NaN

// エラー処理の例
function safeHypot(x, y) {
  const result = Math.hypot(x, y);
  if (isNaN(result)) {
    throw new Error('Invalid arguments: Numbers expected');
  }
  return result;
}

パフォーマンスの考慮

大量の計算が必要な場合は、以下のように最適化することができます:

// 距離の比較だけが必要な場合は、Math.hypot()を使わない
function isWithinRange(point1, point2, range) {
  const dx = point2.x - point1.x;
  const dy = point2.y - point1.y;
  return (dx * dx + dy * dy) <= (range * range);
}

ブラウザ互換性

Math.hypot()は比較的新しい機能ですが、現代的なブラウザでは広くサポートされています:

  • Chrome 38以降
  • Firefox 27以降
  • Safari 8以降
  • Edge 12以降

古いブラウザをサポートする必要がある場合は、以下のようなポリフィルを使用できます:

if (Math.hypot === undefined) {
  Math.hypot = function() {
    var sum = 0;
    var i = arguments.length;
    while (i--) {
      sum += arguments[i] * arguments[i];
    }
    return Math.sqrt(sum);
  };
}

まとめ

Math.hypot()は直線距離の計算を簡単かつ正確に行える便利な関数です。特に:

  • 2点間の距離計算が簡単に
  • 複数次元での距離計算にも対応
  • ゲーム開発や幾何学的な計算に最適

実装時はブラウザの互換性とパフォーマンスを考慮することで、より効果的に活用することができます。