官术网_书友最值得收藏!

2D lines

A line is the shortest straight path that connects two points. A line can be defined by a point on the line and a slope; this is called the slope intercept form. An actual line has no ends; it extends infinitely in both directions. This is not what we intuitively think of as a line. Instead, we want to define a line using a Start Point and an End Point. This is called a Line Segment:

2D lines

Getting ready

Even though we are implementing a line segment, in code we are going to refer to it as a line. We rarely, if ever, use real lines to detect collisions, but we often use line segments. The Line2D structure we are about to create will consist of two points, where the line starts and where it ends.

How to do it…

Follow these steps to define a two-dimensional line, and the helper functions we will need to work with lines:

  1. Define the Line2D structure in Geometry2D.h.
    typedef struct Line2D {
       Point2D start;
       Point2D end;
    
       inline Line2D() { }
       inline Line2D(const Point2D& s, const Point2D& e) 
          :start(s), end(e) {}
    } Line2D;
  2. Declare the helper functions, Length and LengthSq in Geometry2D.h:
    float Length(const Line2D& line);
    float LengthSq(const Line2D& line);
  3. Create a new .cpp file, Geometry2D.cpp. Include the following headers, and define the CMP macro for comparing floats:
    #include "Geometry2D.h"
    #include "matrices.h"
    #include <cmath>
    #include <cfloat>
    
    #define CMP(x, y) \
       (fabsf((x)–(y)) <= FLT_EPSILON * \
       fmaxf(1.0f, fmaxf(fabsf(x), fabsf(y))))
  4. Implement the Length and LengthSq functions in Geometry2D.cpp:
    float Length(const Line2D& line) {
       return Magnitude(line.end - line.start);
    }
    
    float LengthSq(const Line2D& line) {
       return MagnitudeSq(line.end - line.start);
    }

How it works…

The Line2D structure has two constructors, we can create a line segment with no arguments, or we can specify the start and end points of the line. We also implemented two line-related helper functions: Length and LengthSq. These functions return the length and squared length of the line, respectively.

主站蜘蛛池模板: 望城县| 开阳县| 锡林郭勒盟| 民勤县| 深圳市| 和静县| 阿拉善左旗| 皮山县| 无棣县| 富顺县| 祥云县| 太仆寺旗| 德江县| 高邑县| 金湖县| 江川县| 望江县| 察雅县| 安福县| 定结县| 科尔| 新丰县| 历史| 桐梓县| 水富县| 天柱县| 德阳市| 莱阳市| 本溪市| 新建县| 临猗县| 尚志市| 藁城市| 长武县| 罗源县| 延川县| 东乌珠穆沁旗| 蒙山县| 芜湖市| 瑞金市| 海安县|