สมมติมี Rectangle ABCD แต่รู้แค่ Midpoints P และ Q และความยาวด้าน L

ต้องการหา Coordinates ของ A, B, C, D จาก P, Q และ L ตัวอย่าง P=(1,0), Q=(1,2), L=2 ได้ A,B,C,D = (0,0), (0,2), (2,2), (2,0)
มี 3 กรณี:
- Rectangle แนวนอน AD, BC ขนานแกน X
- Rectangle แนวตั้ง AD, BC ขนานแกน Y
- Rectangle 傾斜 กับแกน
กรณีที่ 3: หา Slope จาก P, Q ได้สมการเส้นตรงผ่าน AD แล้วใช้ Distance Formula หาจุดมุม
$$Slope\:of\:AD,m=\frac{px-qx}{py-qy}$$
$$Displacement\:along\:x\:axis, dx=\frac{L}{2\sqrt{1+m^{2}}}$$
$$Displacement\:along\:y\:axis, dy=\frac{mL}{2\sqrt{1+m^{2}}}$$
ตัวอย่างโค้ด C++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
float x, y;
Point(float a = 0.0f, float b = 0.0f) {
x = a, y = b;
}
};
void printCorners(Point p, Point q, float l) {
Point a, b, c, d;
if (p.x == q.x) {
a.x = p.x - (l/2.0);
d.x = p.x + (l/2.0);
a.y = d.y = p.y;
b.x = q.x - (l/2.0);
c.x = q.x + (l/2.0);
b.y = c.y = q.y;
} else if (p.y == q.y) {
a.y = p.y - (l/2.0);
d.y = p.y + (l/2.0);
a.x = d.x = p.x;
b.y = q.y - (l/2.0);
c.y = q.y + (l/2.0);
b.x = c.x = q.x;
} else {
float m = (p.x-q.x)/float(q.y-p.y);
float dx = (l / sqrt(1+(m*m))) * 0.5;
float dy = m*dx;
a.x = p.x - dx; a.y = p.y - dy;
d.x = p.x + dx; d.y = p.y + dy;
b.x = q.x - dx; b.y = q.y - dy;
c.x = q.x + dx; c.y = q.y + dy;
}
cout << "A (" << a.x << ", " << a.y << ")\n"
<< "B (" << b.x << ", " << b.y << ")\n"
<< "C (" << c.x << ", " << c.y << ")\n"
<< "D (" << d.x << ", " << d.y << ")\n";
}
int main() {
Point p(1, 1), q(-1, -1);
printCorners(p, q, 2*sqrt(2));
}
ผลลัพธ์
A (0, 2) B (-2, 0) C (0, -2) D (2, 0)