if (! paths[i].empty()) { double cur_x = agvs[i].current_x; double cur_y = agvs[i].current_y; Node* next_node = paths[i][0]; float speed = agvs[i].getSpeed(); float distance = sqrt(pow(next_node->x - cur_x, 2) + pow(next_node->y - cur_y, 2)); int steps = ceil(distance / (speed * 0.015)); // 计算需要移动的步数 float power_consumption = distance / 20; //_MAP[cur_x][cur_y] = 1; for (int j = 1; j <= steps; j++) { float time = j *100 / speed; // 每步所需时间 QTimer::singleShot(time, this, &, i, next_node, cur_x, cur_y, power_consumption, j, steps { // if (j == 1) { // //离开当前位置时将标记设为0 // //MAP[cur_x][cur_y] = 0; // } float ratio = static_cast<float>(j) / steps; double new_x = cur_x + ratio * (next_node->x - cur_x); double new_y = cur_y + ratio * (next_node->y - cur_y); agvs[i].setCurrentX(new_x); agvs[i].setCurrentY(new_y); std:: cout <<"AGV"<<"("<< new_x << "," << new_y << ")" << endl; // 更新电量 agvs[i].setpower(agvs[i].power - power_consumption / steps); this->update(); // 在窗口中重绘 }); } }小車隨著new_x的坐標移動,爲什麽會出現倒退的情況,怎麽修改代碼
时间: 2024-01-31 17:04:23 浏览: 31
在代码中,小车的移动是通过计算每一步所需的时间,然后使用`QTimer::singleShot`函数设置定时器,在每个时间间隔内更新小车的位置实现的。如果出现小车出现倒退的情况,可能是因为小车在前面的步骤中没有完全到达目标节点,但下一步已经开始了,导致小车回到了之前的位置。
为了解决这个问题,可以在计算下一步所需的时间之前,先判断小车是否已经到达了目标节点。如果小车已经到达了目标节点,那么就可以将该节点从路径列表中删除,然后再计算下一步的位置。
修改代码如下:
```c++
if (! paths[i].empty()) {
double cur_x = agvs[i].current_x;
double cur_y = agvs[i].current_y;
Node* next_node = paths[i][0];
float speed = agvs[i].getSpeed();
float distance = sqrt(pow(next_node->x - cur_x, 2) + pow(next_node->y - cur_y, 2));
int steps = ceil(distance / (speed * 0.015)); // 计算需要移动的步数
float power_consumption = distance / 20;
//_MAP[cur_x][cur_y] = 1;
// 判断是否到达目标节点
if (distance <= 0.01) {
paths[i].erase(paths[i].begin());
return;
}
for (int j = 1; j <= steps; j++) {
float time = j *100 / speed;
QTimer::singleShot(time, this, &, i, next_node, cur_x, cur_y, power_consumption, j, steps {
float ratio = static_cast<float>(j) / steps;
double new_x = cur_x + ratio * (next_node->x - cur_x);
double new_y = cur_y + ratio * (next_node->y - cur_y);
agvs[i].setCurrentX(new_x);
agvs[i].setCurrentY(new_y);
std:: cout <<"AGV"<<"("<< new_x << "," << new_y << ")" << endl;
// 更新电量
agvs[i].setpower(agvs[i].power - power_consumption / steps);
this->update(); // 在窗口中重绘
});
}
}
```
这样,当小车到达目标节点时,就会将该节点从路径列表中删除,避免了出现倒退的情况。