- Game Physics Cookbook
- Gabor Szauer
- 325字
- 2021-04-02 20:27:34
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:

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:
- Define the
Line2D
structure inGeometry2D.h
.typedef struct Line2D { Point2D start; Point2D end; inline Line2D() { } inline Line2D(const Point2D& s, const Point2D& e) :start(s), end(e) {} } Line2D;
- Declare the helper functions,
Length
andLengthSq
inGeometry2D.h
:float Length(const Line2D& line); float LengthSq(const Line2D& line);
- Create a new .
cpp
file,Geometry2D.cpp
. Include the following headers, and define theCMP
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))))
- Implement the
Length
andLengthSq
functions inGeometry2D.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.
- Visual C++串口通信開發入門與編程實踐
- C和C++安全編碼(原書第2版)
- INSTANT Weka How-to
- Python 3網絡爬蟲實戰
- Learning Firefox OS Application Development
- Java Web基礎與實例教程
- R的極客理想:工具篇
- Python算法從菜鳥到達人
- Swift語言實戰精講
- C語言開發基礎教程(Dev-C++)(第2版)
- Java EE企業級應用開發教程(Spring+Spring MVC+MyBatis)
- Getting Started with Polymer
- Mastering Apache Camel
- Mastering Embedded Linux Programming
- WordPress Search Engine Optimization(Second Edition)