二線の交差する点を検出(2D)

二線の交差する点を検出(2D)


二線の交差する点を求めたいと考えた場合

直線A 原点x1,y1 傾きm1
直線B 原点x2,y2 傾きm2
とした場合、

公式
x = ( m1 × x1 - m2 × x2 + y2 - y1 ) / (m1 - m2)
y = m1 × ( x - x1 ) + y1
で交点を求める事が出来る

lineIntersect1.jpg

using UnityEngine;
using System.Collections;

public class test1 : MonoBehaviour {


  void Start () {

      print( LineIntersect(new Vector2(1,1),new Vector2(3,3),new Vector2(3,1),new Vector2(1,3)) );    
   }

  Vector2 LineIntersect(Vector2 origin1,Vector2 direction1,Vector2 origin2,Vector2 direction2){
       Vector2 intersect = Vector2.zero;

      Vector2 slopeV1 = origin1 - direction1;
       float slopeF1 = slopeV1.y / slopeV1.x;

      Vector2 slopeV2 = origin2 - direction2;
       float slopeF2 = slopeV2.y / slopeV2.x;

      intersect.x = (slopeF1 * origin1.x - slopeF2 *origin2.x + origin2.y - origin1.y)/(slopeF1 - slopeF2);
       intersect.y = slopeF1*(intersect.x - origin1.x)+origin1.y;

      return intersect;
   }
}

出力
(2.0, 2.0)

上記のコードは内部で「傾き」が作成されているので距離は無限として交点が検出されている事に注意
またお互いの線の関係が平行である事は想定されていない

unityの標準機能でPhysics2D.Raycastクラスが存在する
これらの機能を利用するとバウンドやコライダーに対して衝突や位置等を検出出来ますがレイ同士の判定は出来ない?

(旧)二線の交差する点を検出(2D)


線分Aと線分Bの交点を出力する
LineIntersect(点A,傾きA,点B,傾きB)

using UnityEngine;
using System.Collections;

public class Math1 : MonoBehaviour
{
      void Start ()
       {
               print (LineIntersect (new Vector2 (1, 1), 2, new Vector2 (1, 1), -2));
               print (LineIntersect (new Vector2 (11, 5), 2, new Vector2 (5, 5), -4));
       }

      Vector2 LineIntersect (Vector2 pointA, float deltaA, Vector2 pointB, float deltaB)
       {
               Vector2 answer;
               answer.x = (deltaA * pointA.x - deltaB * pointB.x + pointB.y - pointA.y) / (deltaA - deltaB);
               answer.y = deltaA * (answer.x - pointA.x) + pointA.y;

              return answer;
       }
}

  • 最終更新:2014-01-15 23:13:44

このWIKIを編集するにはパスワード入力が必要です

認証パスワード