1. 程式人生 > >程式設計練習:判斷點是否在矩形內

程式設計練習:判斷點是否在矩形內

轉載自:

  最近在做遊戲伺服器中技能模組,往往要掃描一個區域,判斷&
  npc是不是在我這個區域內,在的話就發傷害。
  就需要實現一下,對於一個點是否在矩形內的判斷。
只需要判斷該點是否在上下兩條邊和左右兩條邊之間就行,判斷一個點是否在兩條線段之間夾著,就轉化成,判斷一個點是否在某條線段的一邊上,就可以利  用叉乘的方向性,來判斷夾角是否超過了180度 如下圖:
這裡寫圖片描述
  只要判斷(p1 p2 X p1 p ) * (p3 p4 X p3 p1) >= 0 就說明p在p1p2,p3p4中間夾著,同理計算另兩邊就可以了
  最後就是隻需要判斷 (p1 p2 X p1 p ) * (p3 p4 X p3 p1) >= 0 && (p2 p3 X p2 p ) * (p4 p1 X p4 p) >= 0 ;

// ConsoleApplication18.cpp : Defines the entry point for the console application.  
    //判斷一個點是否在矩形內部  

    #include "stdafx.h"  
    #include "iostream"  
    struct Point  
    {  
        float x;  
        float y;  
        Point(float x,float y)  
        {  
            this->x = x;  
            this
->y = y; } }; // 計算 |p1 p2| X |p1 p| float GetCross(Point& p1, Point& p2,Point& p) { return (p2.x - p1.x) * (p.y - p1.y) -(p.x - p1.x) * (p2.y - p1.y); } //判斷點是否在5X5 以原點為左下角的正方形內(便於測試) bool IsPointInMatrix(Point& p) { Point p1(0
,5); Point p2(0,0); Point p3(5,0); Point p4(5,5); return GetCross(p1,p2,p) * GetCross(p3,p4,p) >= 0 && GetCross(p2,p3,p) * GetCross(p4,p1,p) >= 0; //return false; } using namespace std; int _tmain(int argc, _TCHAR* argv[]) { while(true) { Point testPoint(0,0); cout << "enter the point :" << endl; cin >> testPoint.x >> testPoint.y; cout << "the point is : "<< testPoint.x << " "<< testPoint.y << endl; cout << "the point is " << (IsPointInMatrix(testPoint)? "in the Matrix .": "not in the matrix ." )<< endl; } return 0; }