在此程序中,球体将围绕由立方体包围的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++;
}
答案 0 :(得分:0)
在下面的循环中,您要多次递增i
,您确定要有这么多元素吗?
while(i != doubleList.end())
{
答案 1 :(得分:0)
如果s
和j
位于列表中的相同位置,则会删除j
,这会使s
无效。
您不必每次都从头开始j
,因为您已经将它与s
前面的每个元素进行了比较。
我想替换
j = sphereList.begin();
带
j = s;
应该足够了。