gpt4 book ai didi

c++ - 如何实现碰撞检测

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:52 25 4
gpt4 key购买 nike

我正在创建一个模拟机器人在地图上移动的程序。我有一个环境课程,其中包含机器人和机器人可能遇到的障碍。目前,我有用于机器人的类对象和障碍物,并且我有一个函数告诉我它们是否碰撞(返回true / false)。我只是不确定如何将其放入机器人的运动功能中。

机器人是一个正方形,具有一个中心点(x,y)的宽度,长度和某些方向(以度为单位)(fyi,环境类是机器人类的朋友)。障碍物是具有中心点(x,y)和半径的圆。

  class Environment{
Robot robot;
vector<Obstacle> obstacles;

//random obstacle generation function

bool collision_circle(Obstacle obstacle) {
//Check if the circle intersects any of the corners of the robot
std::vector<Point> points;
points.push_back(robot.top_right);
points.push_back(robot.top_left);
points.push_back(robot.bottom_right);
points.push_back(robot.bottom_left);

Point obst_center(obstacle.return_x(), obstacle.return_y());

for (int i = 0; i < points.size(); i++) {
points[i].set_distance(obst_center);
if (points[i].distance <= obstacle.return_radius()) { return true; }
}

//Sort the points by distance away from the obstacle
std::sort(points.begin(), points.end(), less_than());

//Use the two closest to the obstacle to create a line
double m = (points[0].x - points[1].x) / (points[0].y -
points[1].y);
double b = points[0].y - (m * points[0].x);

//Determine a line perpendicular which intersects the obstacle's
center
double m_perp = 1 / m;
double b_perp = obst_center.y - (m * obst_center.x);

Point on Robot closest to obstacle
double new_x = (b - b_perp) / (m_perp - m);
double new_y = m_perp * new_x + b_perp;

distance between points
double diff_x = obst_center.x - new_x;
double diff_y = obst_center.y - new_y;
double distance = sqrt(pow(diff_x, 2) + pow(diff_y, 2));

if (distance <= obstacle.return_radius()) { return true; }
else { return false; }
}

Environment(Robot& t_robot): robot(t_robot) {}

void forward(double num_inches){
robot.y += num_inches * sin(robot.orientation * convert_deg);
//Convert_deg is a global variable = PI/180
robot.x += num_inches * cos(robot.orientation * convert_deg);
}
//void backward, left, right, etc.
}


我尝试使用前向功能检查经过一定距离的距离后是否与每个障碍物相交(在地图上最多15个),但这使我的程序停滞不前,或者每覆盖一英寸就需要进行数千次计算。我是否在正确的方向上执行此操作?我也将SFML用于图形,但是据我所知,它仅支持边界框碰撞检测。另外,我希望图形成为该程序的附属内容。我正在编写此程序,以便我可以为机器人的运动创建和测试程序,并最终希望仅运行示例并告知其是否有效,并在需要时观看重放。

最佳答案

您不需要绝对值来避免-ve值吗?
double m =(points [0] .x-points [1] .x)/(points [0] .y-
      points [1] .y);

关于c++ - 如何实现碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57280942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com