我一直在努力探測遊戲中物體之間的碰撞。現在一切都是垂直的,但是希望保持其他運動的選擇開放。這是經典的2D立體空間射擊遊戲。偶發性碰撞檢測
現在我遍歷每個對象,碰撞檢測:
for(std::list<Object*>::iterator iter = mObjectList.begin(); iter != mObjectList.end();) {
Object *m = (*iter);
for(std::list<Object*>::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<float> ourMidPoint = getAbsoluteMidPoint();
Vector<float> 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<float> ourMidPoint = getAbsoluteMidPoint();
Vector<float> 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;
}
}
你有沒有尚未作出變更處於Beta的回答最新版本的建議(即不平方的總和半徑兩次)?如果這解決了你的問題,你應該接受Beta的答案。如果沒有,你應該指出它還沒有工作。 – 2011-03-30 12:00:25