在这个程序中,球体将围绕一个由立方体包围的 3d 空间移动。球体将移动,直到它们撞到墙壁或另一个球体。如果他们撞到墙上,他们就会被摧毁。如果他们击中另一个球体,较小的球体将被摧毁。
球体在 x、y、z 坐标中给出,半径为 r,运动的 dx、dy、dz。
该程序的一般要点是循环遍历球体对象列表并使用距离公式查看它是否小于检测碰撞的半径。
无论如何,我在运行时一直在 Visual Studio 中收到一个错误,说“列表迭代器不可递增。但是,该程序在 Linux g++ 编译器上运行时没有错误。看起来在程序工作时尝试检测球体碰撞时会出现问题当该部分被注释掉时。
// This is where our spheres are moved
s = sphereList.begin(); //set iterator to beginning of list
while(s != sphereList.end()) //This loop moves the spheres
{
bool firstRun = true;
double x,y,z,r,xj,yj,zj,dist,radii,area1,area2; //Temp x,y,z,r
Point newCenter; //Temp Center for movement calculatio n
x = s->getX()+s->getdx();
y = s->getY()+s->getdy();
z = s->getZ()+s->getdz();
r = s->getRadius();
newCenter.setX(x);
newCenter.setY(y);
newCenter.setZ(z);
s->setCenter(newCenter); //replaces existing sphere with new coordinates
//check if the sphere has reached the edge of the cube at 0 or 1000 units
if(x+r >= MAX_CUBE || x-r <= MIN_CUBE || y+r >= MAX_CUBE || y-r <= MIN_CUBE || z+r >= MAX_CUBE || z-r <= MIN_CUBE)
{
cout << " " << s->getElement() << " " << (int)time << " " << "Boundary" << endl;
s = sphereList.erase(s);
time = 1 * TIME_VALUE;
}
std::list<Sphere>::iterator j = sphereList.begin(); //second iterator
j++;
while(j != sphereList.end())
{
xj = j->getX();
yj = j->getY();
zj = j->getZ();
dist = sqrt(((x-xj)*(x-xj))+((y-yj)*(y-yj))+((z-zj)*(z-zj)));
//cout << dist << endl;
radii = s->getRadius() + j->getRadius();
if(dist < radii)
{
if(s->getRadius() < j->getRadius())
{
cout << " " << s->getElement() << " " << (int)time << " " << "Collision" << endl;
s = sphereList.erase(s);
time = 1 * TIME_VALUE;
break;
}
else
{
cout << " " << j->getElement() << " " << (int)time << " " << "Collision" << endl;
j = sphereList.erase(j);
time = 1 * TIME_VALUE;
break;
}
}
j++;
}
time++;
}