我一直在尝试用 C/X11/OpenGL 编写 FPS,但我遇到的问题是计算子弹击中的位置。我使用了一种可怕的技术,它只是有时有效:
pos size, p;
size.x = 0.1;
size.z = 0.1; // Since the game is technically top-down (but in a 3D perspective)
// Positions are in X/Z, no Y
float f; // Counter
float d = FIRE_MAX + 1 /* Shortest Distance */, d1 /* Distance being calculated */;
x = 0; // Index of object to hit
for (f = 0.0; f < FIRE_MAX; f += .01) {
// Go forwards
p.x = player->pos.x + f * sin(toRadians(player->rot.x));
p.z = player->pos.z - f * cos(toRadians(player->rot.x));
// Get all objects that collide with the current position of the bullet
short* objs = _colDetectGetObjects(p, size, objects);
for (i = 0; i < MAX_OBJECTS; i++) {
if (objs[i] == -1) {
continue;
}
// Check the distance between the object and the player
d1 = sqrt(
pow((objects[i].pos.x - player->pos.x), 2)
+ pow((objects[i].pos.z - player->pos.z),
2));
// If it's closer, set it as the object to hit
if (d1 < d) {
x = i;
d = d1;
}
}
// If there was an object, hit it
if (x > 0) {
hit(&objects[x], FIRE_DAMAGE, explosions, currtime);
break;
}
}
它的工作原理是创建一个 for 循环并计算可能与子弹当前所在位置发生碰撞的任何对象。当然,这非常慢,有时甚至不起作用。
计算子弹击中位置的首选方法是什么?我想过画一条线,看看是否有任何物体与那条线碰撞,但我不知道如何进行这种碰撞检测。
编辑: 我想我的问题是:如何计算最近的直线碰撞对象(可能不是直线 45/90 度角)?或者有没有更简单的方法来计算子弹击中的位置?子弹有点像激光,因为重力不会影响它(写一个老式游戏,所以我不希望它太逼真)
最佳答案
对于每一个你想要被击中的对象,定义一个边界对象。 简单的例子是球体或盒子。 然后,您必须实现光线球面或光线盒相交。
例如看看line-sphere intersection . 对于盒子,您可以测试四个边界线,但有针对 axis aligned boxes 优化的算法。 .
有了这个,像你已经做的那样继续。对于场景中的每个对象,检查交叉点,如果相交,则比较与先前相交对象的距离,取第一个被击中的对象。
相交算法为您提供射线参数(hit_position = ray_origin + t * ray_direction
的值 t),您可以使用它来比较距离。
关于c - 如何计算子弹击中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13534519/