碰撞检测C语言,c – 偶发性碰撞检测

本文介绍了一种使用C语言进行2D游戏对象碰撞检测的方法。通过循环遍历游戏对象列表并检查每个对象之间的碰撞,利用中点和半径来判断碰撞是否发生。然而,作者遇到了偶发性的碰撞检测失败问题,尤其是当对象接近屏幕底部时。为解决此问题,更新了碰撞检测算法,通过计算两点之间的距离和两圆半径之和的平方来判断是否相交。尽管如此,仍然存在不一致的碰撞检测结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我一直在努力检测游戏中对象之间的碰撞.现在所有东西都是垂直的,但是希望保持其他运动的选择.这是经典的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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值