1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
| // Game_04_CollisionDetection.cpp
// 碰撞检测基础实现
// 编译:g++ Game_04_CollisionDetection.cpp -std=c++17 -o Game_04_CollisionDetection
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <optional>
#include <iomanip>
// ============================================================
// 数学工具
// ============================================================
struct Vec2 {
float x, y;
Vec2(float x = 0, float y = 0) : x(x), y(y) {}
Vec2 operator+(const Vec2& other) const {
return Vec2(x + other.x, y + other.y);
}
Vec2 operator-(const Vec2& other) const {
return Vec2(x - other.x, y - other.y);
}
Vec2 operator*(float scalar) const {
return Vec2(x * scalar, y * scalar);
}
float dot(const Vec2& other) const {
return x * other.x + y * other.y;
}
float length() const {
return std::sqrt(x * x + y * y);
}
Vec2 normalized() const {
float len = length();
if (len < 0.0001f) return Vec2(0, 0);
return Vec2(x / len, y / len);
}
// 点到线段的最近点
static Vec2 closestPointOnSegment(const Vec2& point,
const Vec2& segStart,
const Vec2& segEnd) {
Vec2 seg = segEnd - segStart;
float t = std::max(0.0f, std::min(1.0f,
(point - segStart).dot(seg) / seg.dot(seg)));
return segStart + seg * t;
}
};
struct Vec3 {
float x, y, z;
Vec3(float x = 0, float y = 0, float z = 0) : x(x), y(y), z(z) {}
Vec3 operator+(const Vec3& other) const {
return Vec3(x + other.x, y + other.y, z + other.z);
}
Vec3 operator-(const Vec3& other) const {
return Vec3(x - other.x, y - other.y, z - other.z);
}
Vec3 operator*(float scalar) const {
return Vec3(x * scalar, y * scalar, z * scalar);
}
float dot(const Vec3& other) const {
return x * other.x + y * other.y + z * other.z;
}
Vec3 cross(const Vec3& other) const {
return Vec3(
y * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x
);
}
float length() const {
return std::sqrt(x * x + y * y + z * z);
}
Vec3 normalized() const {
float len = length();
if (len < 0.0001f) return Vec3(0, 0, 0);
return Vec3(x / len, y / len, z / len);
}
};
// ============================================================
// 包围体(Bounding Volume)
// ============================================================
// 轴对齐包围盒(AABB - Axis-Aligned Bounding Box)
struct AABB2D {
Vec2 min; // 左下角
Vec2 max; // 右上角
AABB2D(const Vec2& min, const Vec2& max) : min(min), max(max) {}
static AABB2D fromCenter(const Vec2& center, float halfWidth, float halfHeight) {
return AABB2D(
Vec2(center.x - halfWidth, center.y - halfHeight),
Vec2(center.x + halfWidth, center.y + halfHeight)
);
}
float width() const { return max.x - min.x; }
float height() const { return max.y - min.y; }
Vec2 center() const { return (min + max) * 0.5f; }
// AABB vs AABB
static bool intersects(const AABB2D& a, const AABB2D& b) {
if (a.max.x < b.min.x || a.min.x > b.max.x) return false;
if (a.max.y < b.min.y || a.min.y > b.max.y) return false;
return true;
}
// 详细碰撞检测(返回MTV - Minimum Translation Vector)
static std::optional<Vec2> collisionInfo(const AABB2D& a, const AABB2D& b) {
if (!intersects(a, b)) return std::nullopt;
// 计算重叠量
float overlapX = std::min(a.max.x - b.min.x, b.max.x - a.min.x);
float overlapY = std::min(a.max.y - b.min.y, b.max.y - a.min.y);
// 选择最小分离轴
if (overlapX < overlapY) {
// 沿X轴分离
bool aIsLeft = a.center().x < b.center().x;
return Vec2(aIsLeft ? -overlapX : overlapX, 0);
} else {
// 沿Y轴分离
bool aIsBottom = a.center().y < b.center().y;
return Vec2(0, aIsBottom ? -overlapY : overlapY);
}
}
};
// 圆形碰撞体
struct Circle {
Vec2 center;
float radius;
Circle(const Vec2& center, float radius)
: center(center), radius(radius) {}
static bool intersects(const Circle& a, const Circle& b) {
Vec2 diff = a.center - b.center;
float distSq = diff.dot(diff);
float radiusSum = a.radius + b.radius;
return distSq < radiusSum * radiusSum;
}
// 圆 vs AABB
static bool intersects(const Circle& circle, const AABB2D& box) {
Vec2 closest = Vec2(
std::max(box.min.x, std::min(circle.center.x, box.max.x)),
std::max(box.min.y, std::min(circle.center.y, box.max.y))
);
Vec2 diff = circle.center - closest;
return diff.dot(diff) < circle.radius * circle.radius;
}
};
// 定向包围盒(OBB - Oriented Bounding Box)
struct OBB2D {
Vec2 center;
Vec2 halfExtents; // 半宽半高
Vec2 axes[2]; // 局部坐标轴(单位向量)
OBB2D(const Vec2& center, const Vec2& halfExtents, float angle) :
center(center), halfExtents(halfExtents) {
axes[0] = Vec2(std::cos(angle), std::sin(angle));
axes[1] = Vec2(-std::sin(angle), std::cos(angle));
}
// 获取OBB的四个顶点
std::vector<Vec2> getVertices() const {
std::vector<Vec2> verts(4);
for (int i = 0; i < 4; i++) {
Vec2 offset(
(i % 2 == 0 ? 1 : -1) * halfExtents.x,
(i / 2 == 0 ? 1 : -1) * halfExtents.y
);
// 将偏移量转换到世界坐标
verts[i] = center + Vec2(
axes[0].x * offset.x + axes[1].x * offset.y,
axes[0].y * offset.x + axes[1].y * offset.y
);
}
return verts;
}
// OBB vs OBB(SAT - Separating Axis Theorem)
static bool intersects(const OBB2D& a, const OBB2D& b) {
// 获取所有测试轴(两个OBB的4个轴)
std::vector<Vec2> testAxes = {a.axes[0], a.axes[1], b.axes[0], b.axes[1]};
for (const Vec2& axis : testAxes) {
if (!overlapsOnAxis(a, b, axis)) {
return false; // 找到分离轴,无碰撞
}
}
return true; // 所有轴都重叠,有碰撞
}
private:
static bool overlapsOnAxis(const OBB2D& a, const OBB2D& b, const Vec2& axis) {
// 投影到轴上并检查区间是否重叠
// 计算每个OBB在轴上的投影区间半径(半宽)
float aHalfExtent = getOBBHalfExtentOnAxis(a, axis);
float bHalfExtent = getOBBHalfExtentOnAxis(b, axis);
// 投影中心
float aProjCenter = a.center.dot(axis);
float bProjCenter = b.center.dot(axis);
// 检查区间是否重叠:中心距离 <= 半宽之和
return std::abs(aProjCenter - bProjCenter) <= (aHalfExtent + bHalfExtent);
}
// 计算OBB在给定轴上的投影半宽
static float getOBBHalfExtentOnAxis(const OBB2D& box, const Vec2& axis) {
return std::abs(box.halfExtents.x * box.axes[0].dot(axis)) +
std::abs(box.halfExtents.y * box.axes[1].dot(axis));
}
};
// ============================================================
// 碰撞系统
// ============================================================
class CollisionWorld {
private:
struct RigidBody {
Vec2 position;
Vec2 velocity;
float mass;
bool isStatic;
enum class ShapeType { CIRCLE, AABB } shapeType;
union {
Circle circle;
AABB2D aabb;
};
RigidBody(const Vec2& pos, float m, bool staticBody)
: position(pos), velocity(0, 0), mass(m), isStatic(staticBody) {}
virtual ~RigidBody() {}
};
struct CircleBody : RigidBody {
CircleBody(const Vec2& pos, float radius, float m, bool staticBody)
: RigidBody(pos, m, staticBody) {
shapeType = ShapeType::CIRCLE;
new (&circle) Circle(pos, radius);
}
};
struct AABBBody : RigidBody {
float halfWidth, halfHeight;
AABBBody(const Vec2& pos, float hw, float hh, float m, bool staticBody)
: RigidBody(pos, m, staticBody), halfWidth(hw), halfHeight(hh) {
shapeType = ShapeType::AABB;
new (&aabb) AABB2D(Vec2(pos.x - hw, pos.y - hh),
Vec2(pos.x + hw, pos.y + hh));
}
};
std::vector<std::unique_ptr<RigidBody>> bodies;
public:
~CollisionWorld() {
for (auto& body : bodies) {
if (body->shapeType == RigidBody::ShapeType::AABB) {
body->aabb.~AABB2D();
}
}
}
size_t addCircle(const Vec2& pos, float radius, float mass = 1.0f, bool isStatic = false) {
bodies.push_back(std::make_unique<CircleBody>(pos, radius, mass, isStatic));
return bodies.size() - 1;
}
size_t addAABB(const Vec2& pos, float hw, float hh, float mass = 1.0f, bool isStatic = false) {
bodies.push_back(std::make_unique<AABBBody>(pos, hw, hh, mass, isStatic));
return bodies.size() - 1;
}
// 简单物理更新
void update(float dt) {
for (auto& body : bodies) {
if (body->isStatic) continue;
// 简单重力 + 速度更新位置
body->velocity.y -= 9.8f * dt;
body->position = body->position + body->velocity * dt;
// 更新碰撞体位置
if (body->shapeType == RigidBody::ShapeType::CIRCLE) {
body->circle.center = body->position;
} else if (body->shapeType == RigidBody::ShapeType::AABB) {
float hw = static_cast<AABBBody*>(body.get())->halfWidth;
float hh = static_cast<AABBBody*>(body.get())->halfHeight;
new (&body->aabb) AABB2D(
Vec2(body->position.x - hw, body->position.y - hh),
Vec2(body->position.x + hw, body->position.y + hh)
);
}
}
}
// 碰撞检测
void checkCollisions() {
std::cout << "\n🔍 开始碰撞检测..." << std::endl;
for (size_t i = 0; i < bodies.size(); i++) {
for (size_t j = i + 1; j < bodies.size(); j++) {
bool collided = false;
auto& a = bodies[i];
auto& b = bodies[j];
// 根据形状类型选择检测方法
if (a->shapeType == RigidBody::ShapeType::CIRCLE &&
b->shapeType == RigidBody::ShapeType::CIRCLE) {
collided = Circle::intersects(a->circle, b->circle);
} else if (a->shapeType == RigidBody::ShapeType::AABB &&
b->shapeType == RigidBody::ShapeType::AABB) {
collided = AABB2D::intersects(a->aabb, b->aabb);
} else if (a->shapeType == RigidBody::ShapeType::CIRCLE &&
b->shapeType == RigidBody::ShapeType::AABB) {
collided = Circle::intersects(a->circle, b->aabb);
} else if (a->shapeType == RigidBody::ShapeType::AABB &&
b->shapeType == RigidBody::ShapeType::CIRCLE) {
collided = Circle::intersects(b->circle, a->aabb);
}
if (collided) {
std::cout << "💥 碰撞!物体 " << i << " 和物体 " << j;
if (a->isStatic) std::cout << " (静态)";
if (b->isStatic) std::cout << " (静态)";
std::cout << std::endl;
}
}
}
}
// 打印世界状态
void printState() const {
std::cout << "\n📊 世界状态:" << std::endl;
for (size_t i = 0; i < bodies.size(); i++) {
const auto& body = bodies[i];
std::cout << " 物体 " << i << ": 位置("
<< std::fixed << std::setprecision(2)
<< body->position.x << ", "
<< body->position.y << ")";
if (body->shapeType == RigidBody::ShapeType::CIRCLE) {
std::cout << " 圆形(r=" << body->circle.radius << ")";
} else if (body->shapeType == RigidBody::ShapeType::AABB) {
std::cout << " AABB(" << body->aabb.width() << "x" << body->aabb.height() << ")";
}
if (body->isStatic) std::cout << " [静态]";
std::cout << std::endl;
}
}
};
// ============================================================
// 演示
// ============================================================
int main() {
std::cout << "========================================" << std::endl;
std::cout << " 碰撞检测系统演示 " << std::endl;
std::cout << "========================================" << std::endl;
CollisionWorld world;
// 创建一些物体
// 地面(静态AABB)
world.addAABB(Vec2(0, -5), 10, 1, 0, true);
// 球(动态圆形)
size_t ball1 = world.addCircle(Vec2(-2, 5), 0.5f, 1.0f, false);
size_t ball2 = world.addCircle(Vec2(2, 8), 0.8f, 2.0f, false);
// 箱子(动态AABB)
size_t box1 = world.addAABB(Vec2(0, 3), 1, 1, 1.0f, false);
std::cout << "\n🎬 初始状态:" << std::endl;
world.printState();
// 模拟几帧
for (int frame = 1; frame <= 5; frame++) {
std::cout << "\n\n========== 帧 " << frame << " ==========" << std::endl;
world.update(0.016f); // ~60FPS
world.checkCollisions();
world.printState();
}
std::cout << R"(
========================================
碰撞检测算法选择指南
========================================
📦 AABB (轴对齐包围盒):
✅ 检测速度快
✅ 适用于没有旋转的物体
❌ 不适用于斜着的物体
用途: 宽相检测, 静态环境
⭕ 圆形:
✅ 旋转不变性 (圆形转不转都一样)
✅ 检测速度极快
❌ 很多物体不是圆形
用途: 球类, 角色代理, 射线检测
📐 精确多边形:
✅ 最精确
❌ 最慢
用途: 需要精确碰撞的场合 (如格斗游戏)
)" << std::endl;
return 0;
}
|