# RTS游戏核心技术 流场寻路算法详解

#include <iostream>
#include <vector>
#include <queue>
#include <cmath>

using namespace std;

// 定义地图大小
const int mapWidth = 10;
const int mapHeight = 10;

// 定义流速向量结构体
struct FlowVector {
int dx;
int dy;
};

// 生成流场
vector<vector<FlowVector>> generateFlowField() {
vector<vector<FlowVector>> flowField(mapWidth, vector<FlowVector>(mapHeight));

// 在这里可以根据地形、障碍物等因素来生成流场
// 这里简单地初始化为一个向右的流速向量
for (int i = 0; i < mapWidth; i++) {
for (int j = 0; j < mapHeight; j++) {
flowField[i][j].dx = 1;
flowField[i][j].dy = 0;
}
}

return flowField;
}

// 定义节点结构体
struct Node {
int x, y;
double cost;
bool operator<(const Node& other) const {
return cost > other.cost;
}
};

// A*路径搜索
vector<pair<int, int>> findPath(vector<vector<FlowVector>>& flowField, pair<int, int> start, pair<int, int> target) {
vector<pair<int, int>> path;
priority_queue<Node> pq;
vector<vector<double>> cost(mapWidth, vector<double>(mapHeight, INFINITY));
vector<vector<pair<int, int>>> parent(mapWidth, vector<pair<int, int>>(mapHeight, make_pair(-1, -1)));

pq.push({start.first, start.second, 0});
cost[start.first][start.second] = 0;

while (!pq.empty()) {
Node cur = pq.top();
pq.pop();

if (cur.x == target.first && cur.y == target.second) {
// 从终点回溯路径
pair<int, int> currPos = {cur.x, cur.y};
while (currPos != start) {
path.push_back(currPos);
currPos = parent[currPos.first][currPos.second];
}
path.push_back(start);
reverse(path.begin(), path.end());
break;
}

for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
if (dx == 0 && dy == 0) continue;
int nx = cur.x + dx;
int ny = cur.y + dy;
if (nx >= 0 && nx < mapWidth && ny >= 0 && ny < mapHeight) {
double newCost = cur.cost + sqrt(dx*dx + dy*dy) + sqrt(flowField[cur.x][cur.y].dx*dx + flowField[cur.x][cur.y].dy*dy);
if (newCost < cost[nx][ny]) {
cost[nx][ny] = newCost;
parent[nx][ny] = {cur.x, cur.y};
pq.push({nx, ny, newCost});
}
}
}
}
}

return path;
}

int main() {
// 生成流场
vector<vector<FlowVector>> flowField = generateFlowField();

// 设置起点和终点
pair<int, int> start = make_pair(0, 0);
pair<int, int> target = make_pair(9, 9);

// 寻找路径
vector<pair<int, int>> path = findPath(flowField, start, target);

// 打印路径
for (auto p : path) {
cout << "(" << p.first << ", " << p.second << ") ";
}

return 0;
} 

• 6
点赞
• 7
收藏
觉得还不错? 一键收藏
• 0
评论
02-05
01-12 740
03-12
05-17 840
05-20 699
05-22 290
05-19 121
05-23 673
05-20 244
05-23 141
05-23 69
05-23 550

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。