判斷線段是否相交的函數和求直線交點的函數

// ToLineCrossPofloat.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"


#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct POINT
{
 int x;
 int y;
};
/*
判斷兩條線段是否相交(有交點)
*/
bool IsLineSegmentCross(POINT pFirst1, POINT pFirst2, POINT pSecond1, POINT pSecond2)
{
 //每個線段的兩點都在另一個線段的左右不同側,則能斷定線段相交
 //公式對於向量(x1,y1)->(x2,y2),判斷點(x3,y3)在向量的左邊,右邊,還是線上.
 //p=x1(y3-y2)+x2(y1-y3)+x3(y2-y1).p<0 左側, p=0 線上, p>0 右側
 long Linep1,Linep2;
 //判斷pSecond1和pSecond2是否在pFirst1->pFirst2兩側
 Linep1 = pFirst1.x * (pSecond1.y - pFirst2.y) +
  pFirst2.x * (pFirst1.y - pSecond1.y) +
  pSecond1.x * (pFirst2.y - pFirst1.y);
 Linep2 = pFirst1.x * (pSecond2.y - pFirst2.y) +
  pFirst2.x * (pFirst1.y - pSecond2.y) +
  pSecond2.x * (pFirst2.y - pFirst1.y);
 if ( ((Linep1 ^ Linep2) >= 0 ) && !(Linep1==0 && Linep2==0))//符號位異或爲0:pSecond1和pSecond2在pFirst1->pFirst2同側
 {
  return false;
 }
 //判斷pFirst1和pFirst2是否在pSecond1->pSecond2兩側
 Linep1 = pSecond1.x * (pFirst1.y - pSecond2.y) +
  pSecond2.x * (pSecond1.y - pFirst1.y) +
  pFirst1.x * (pSecond2.y - pSecond1.y);
 Linep2 = pSecond1.x * (pFirst2.y - pSecond2.y) +
  pSecond2.x * (pSecond1.y - pFirst2.y) +
  pFirst2.x * (pSecond2.y - pSecond1.y);
 if ( ((Linep1 ^ Linep2) >= 0 ) && !(Linep1==0 && Linep2==0))//符號位異或爲0:pFirst1和pFirst2在pSecond1->pSecond2同側
 {
  return false;
 }
 //否則判爲相交
 return true;
}
/*
求兩直線交點,前提是兩條直線必須有交點
在相交的情況下,可以應付各種情況(垂直、係數等)
*/
POINT GetCrossPoint(POINT p1, POINT p2, POINT q1, POINT q2)
{
 //必須相交求出的纔是線段的交點,但是下面的程序段是通用的
 assert(IsLineSegmentCross(p1,p2,q1,q2));
 /*根據兩點式化爲標準式,進而求線性方程組*/
 POINT crossPoint;
 long tempLeft,tempRight;
 //求x座標
 tempLeft = (q2.x - q1.x) * (p1.y - p2.y) - (p2.x - p1.x) * (q1.y - q2.y);
 tempRight = (p1.y - q1.y) * (p2.x - p1.x) * (q2.x - q1.x) + q1.x * (q2.y - q1.y) * (p2.x - p1.x) - p1.x * (p2.y - p1.y) * (q2.x - q1.x);
 crossPoint.x =(int)( (double)tempRight / (double)tempLeft );
 //求y座標 
 tempLeft = (p1.x - p2.x) * (q2.y - q1.y) - (p2.y - p1.y) * (q1.x - q2.x);
 tempRight = p2.y * (p1.x - p2.x) * (q2.y - q1.y) + (q2.x- p2.x) * (q2.y - q1.y) * (p1.y - p2.y) - q2.y * (q1.x - q2.x) * (p2.y - p1.y);
 crossPoint.y =(int)( (double)tempRight / (double)tempLeft );
 return crossPoint;
}
int main(void)
{
 POINT pointA,pointB,pointC,pointD;
 POINT pointCross;
 bool bCross(false);
 pointA.x = 0;pointA.y = 0;
 pointB.x = 0;pointB.y = 100;

 pointC.x = 350;pointC.y = 10;
 pointD.x = -10;pointD.y = 10;
 bCross = IsLineSegmentCross(pointA,pointB,pointC,pointD);
 if (bCross)
 {
  pointCross = GetCrossPoint(pointA,pointB,pointC,pointD);
  printf("交點座標x=%d,y=%d/n",pointCross.x,pointCross.y);
 }
 else
 {
  printf("They are not crossed!");
 }
 return 0;
}

發佈了67 篇原創文章 · 獲贊 3 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章