以下是一个用C++实现的可以快速判断碰撞的四叉树,支持快速插入和删除元素。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 定义一个矩形
struct Rect {
float x1, y1, x2, y2;
Rect() : x1(0), y1(0), x2(0), y2(0) {}
Rect(float x1_, float y1_, float x2_, float y2_) : x1(x1_), y1(y1_), x2(x2_), y2(y2_) {}
bool contains(float x, float y) const {
return x >= x1 && y >= y1 && x <= x2 && y <= y2;
}
bool intersects(const Rect& other) const {
return x2 >= other.x1 && y2 >= other.y1 && x1 <= other.x2 && y1 <= other.y2;
}
};
// 定义四叉树节点
struct QuadNode {
Rect rect;
vector<Rect> objects;
QuadNode* tl;
QuadNode* tr;
QuadNode* bl;
QuadNode* br;
QuadNode(const Rect& r) : rect(r), tl(nullptr), tr(nullptr), bl(nullptr), br(nullptr) {}
~QuadNode() {
delete tl;
delete tr;
delete bl;
delete br;
}
// 插入矩形
void insert(const Rect& obj) {
if (objects.empty()) {
objects.push_back(obj);
return;
}
if (!tl) {
split();
}
if (tl->rect.contains(obj.x1, obj.y1)) {
tl->insert(obj);
} else if (tr->rect.contains(obj.x1, obj.y1)) {
tr->insert(obj);
} else if (bl->rect.contains(obj.x1, obj.y1)) {
bl->insert(obj);
} else {
br->insert(obj);
}
}
// 删除矩形
void remove(const Rect& obj) {
auto it = find(objects.begin(), objects.end(), obj);
if (it != objects.end()) {
objects.erase(it);
} else if (tl) {
if (tl->rect.contains(obj.x1, obj.y1)) {
tl->remove(obj);
} else if (tr->rect.contains(obj.x1, obj.y1)) {
tr->remove(obj);
} else if (bl->rect.contains(obj.x1, obj.y1)) {
bl->remove(obj);
} else {
br->remove(obj);
}
}
}
// 划分节点
void split() {
float hw = (rect.x2 - rect.x1) / 2.0f;
float hh = (rect.y2 - rect.y1) / 2.0f;
tl = new QuadNode(Rect(rect.x1, rect.y1, rect.x1 + hw, rect.y1 + hh));
tr = new QuadNode(Rect(rect.x1 + hw, rect.y1, rect.x2, rect.y1 + hh));
bl = new QuadNode(Rect(rect.x1, rect.y1 + hh, rect.x1 + hw, rect.y2));
br = new QuadNode(Rect(rect.x1 + hw, rect.y1 + hh, rect.x2, rect.y2));
}
// 查询所有与矩形相交的对象
void query(const Rect& r, vector<Rect>& out) const {
if (rect.intersects(r)) {
for (const auto& obj : objects) {
if (obj.intersects(r)) {
out.push_back(obj);
}
}
}
if (tl) {
tl->query(r, out);
tr->query(r, out);
bl->query(r, out);
br->query(r, out);
}
}
};
// 定义四叉树
class QuadTree {
public:
QuadTree(const Rect& r) : root(r) {}
~QuadTree() {}
// 插入矩形
void insert(const Rect& obj) {
root.insert(obj);
}
// 删除矩形
void remove(const Rect& obj) {
root.remove(obj);
}
// 查询所有与矩形相交的对象
vector<Rect> query(const Rect& r) {
vector<Rect> result;
root.query(r, result);
return result;
}
private:
QuadNode root;
};
int main() {
Rect r(0, 0, 100, 100);
QuadTree tree(r);
Rect obj1(10, 10, 20, 20);
tree.insert(obj1);
Rect obj2(30, 30, 40, 40);
tree.insert(obj2);
Rect queryRect(5, 5, 25, 25);
vector<Rect> result = tree.query(queryRect);
cout << "result size: " << result.size() << endl;
for (const auto& obj : result) {
cout << "(" << obj.x1 << ", " << obj.y1 << ", " << obj.x2 << ", " << obj.y2 << ")" << endl;
}
return 0;
}
以上实现基于递归实现。具体实现细节可参考代码注释。