41
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ある点と多角形の内外判定

Posted at

点と多角形の各点とのなす角の合計が360°になる場合、その点が多角形に内包されている、ということになるらしい。

この判定用の関数をJavaScriptで書いたものが以下。

judgeInclusion = function(p1, comparisonArr) {
  var deg = 0;
  var p1x = p1.x;
  var p1y = p1.y;
  
  for (var index = 0; index < comparisonArr.length; index++) {
    var p2x = comparisonArr[index].x;
    var p2y = comparisonArr[index].y;
    if (index < comparisonArr.length - 1) {
      var p3x = comparisonArr[index + 1].x;
      var p3y = comparisonArr[index + 1].y;
    } else {
      var p3x = comparisonArr[0].x;
      var p3y = comparisonArr[0].y;
    }
    
    var ax = p2x - p1x;
    var ay = p2y - p1y;
    var bx = p3x - p1x;
    var by = p3y - p1y;
    
    var cos = (ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by));
    deg += getDegree(Math.acos(cos));
  }
  
  if (Math.round(deg) == 360) {
    return true;
  } else {
    return false;
  }
};

独自の衝突判定を書きたい場合などに使えそう。

デモ

参考

http://kone.vis.ne.jp/diary/diaryb09.html
http://www.sousakuba.com/Programming/gs_two_vector_angle.html

41
42
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?