我一直在努力检测游戏中对象之间的碰撞.现在所有东西都是垂直的,但是希望保持其他运动的选择.这是经典的2d垂直空间射击游戏.
现在我循环遍历每个对象,检查碰撞:
for(std::list::iterator iter = mObjectList.begin(); iter != mObjectList.end();) {
Object *m = (*iter);
for(std::list::iterator innerIter = ++iter; innerIter != mObjectList.end(); innerIter++ ) {
Object *s = (*innerIter);
if(m->getType() == s->getType()) {
break;
}
if(m->checkCollision(s)) {
m->onCollision(s);
s->onCollision(m);
}
}
}
以下是我检查碰撞的方法:
bool checkCollision(Object *other) {
float radius = mDiameter / 2.f;
float theirRadius = other->getDiameter() / 2.f;
Vector ourMidPoint = getAbsoluteMidPoint();
Vector theirMidPoint = other->getAbsoluteMidPoint();
// If the other object is in between our path on the y axis
if(std::min(getAbsoluteMidPoint().y - radius, getPreviousAbsoluteMidPoint().y - radius) <= theirMidPoint.y &&
theirMidPoint.y <= std::max(getAbsoluteMidPoint().y + radius, getPreviousAbsoluteMidPoint().y + radius)) {
// Get the distance between the midpoints on the x axis
float xd = abs(ourMidPoint.x - theirMidPoint.x);
// If the distance between the two midpoints
// is greater than both of their radii together
// then they are too far away to collide
if(xd > radius+theirRadius) {
return false;
} else {
return true;
}
}
return false;
}
问题是它会正确地随机检测碰撞,但其他时候根本检测不到碰撞. if语句不是脱离对象循环,因为对象确实有不同的类型.物体越接近屏幕顶部,就越有可能正确检测到碰撞.靠近屏幕底部,正确检测或甚至根本检测到的机会就越少.但是,并非总是会出现这些情况.对象的直径是巨大的(10和20),看看是否是问题,但它根本没有多大帮助.
编辑 – 更新代码
bool checkCollision(Object *other) {
float radius = mDiameter / 2.f;
float theirRadius = other->getDiameter() / 2.f;
Vector ourMidPoint = getAbsoluteMidPoint();
Vector theirMidPoint = other->getAbsoluteMidPoint();
// Find the distance between the two points from the center of the object
float a = theirMidPoint.x - ourMidPoint.x;
float b = theirMidPoint.y - ourMidPoint.y;
// Find the hypotenues
double c = (a*a)+(b*b);
double radii = pow(radius+theirRadius, 2.f);
// If the distance between the points is less than or equal to the radius
// then the circles intersect
if(c <= radii*radii) {
return true;
} else {
return false;
}
}