球体-球体碰撞检测 -> 反应

8
我需要制作一个算法来检测两个球体何时发生碰撞,以及碰撞后它们各自的方向。比如说,想象一下在台球比赛中开局时,所有球都“随机”地互相碰撞。
因此,在开始编写代码之前,我在想是否已经有这方面的实现了。
谢谢提前帮助!
再见。

1
最困难的部分是并发... - Dr. belisarius
我不关心旋转,我只需要碰撞和“平面反应”。 - Artemix
方向就沿着连接中心的直线。 - Mau
1个回答

13

碰撞部分很容易。检查球心之间的距离是否小于它们半径的总和即可。

至于弹跳,你需要交换对于球体碰撞垂直方向的总速度有贡献的速度量。(假设所有球体质量相等,如果是不同质量的组合则会有所不同)

struct Vec3 {
    double x, y, z;
}

Vec3 minus(const Vec3& v1, const Vec3& v2) {
    Vec3 r;
    r.x = v1.x - v2.x;
    r.y = v1.y - v2.y;
    r.z = v1.z - v2.z;
    return r;
}

double dotProduct(const Vec3& v1, const Vec3& v2) {
    return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}

Vec3 scale(const Vec3& v, double a) {
    Vec3 r;
    r.x = v.x * a;
    r.y = v.y * a;
    r.z = v.z * a;
    return r;
}

Vec3 projectUonV(const Vec3& u, const Vec3& v) {
    Vec3 r;
    r = scale(v, dotProduct(u, v) / dotProduct(v, v));
    return r;
}

int distanceSquared(const Vec3& v1, const Vec3& v2) {
    Vec3 delta = minus(v2, v1);
    return dotProduct(delta, delta);
}

struct Sphere {
    Vec3 position;
    Vec3 velocity;
    int radius;
}

bool doesItCollide(const Sphere& s1, const Sphere& s2) {
    int rSquared = s1.radius + s2.radius;
    rSquared *= rSquared;
    return distanceSquared(s1.position, s2.position) < rSquared;
}

void performCollision(Sphere& s1, Sphere& s2) {
    Vec3 nv1; // new velocity for sphere 1
    Vec3 nv2; // new velocity for sphere 2
    // this can probably be optimised a bit, but it basically swaps the velocity amounts
    // that are perpendicular to the surface of the collistion.
    // If the spheres had different masses, then u would need to scale the amounts of
    // velocities exchanged inversely proportional to their masses.
    nv1 = s1.velocity;
    nv1 += projectUonV(s2.velocity, minus(s2.position, s1.position));
    nv1 -= projectUonV(s1.velocity, minus(s1.position, s2.position));
    nv2 = s2.velocity;
    nv2 += projectUonV(s1.velocity, minus(s2.position, s1.position));
    nv2 -= projectUonV(s2.velocity, minus(s1.position, s2.position));
    s1.velocity = nv1;
    s2.velocity = nv2;
}

编辑:如果您需要更高的准确性,则在碰撞时应计算要将碰撞球体向后移动多远,使它们只接触彼此,然后触发执行碰撞函数。这将确保角度更加准确。


运行得很好 - 但我认为有一个问题:我从10个球开始(没有重叠),只有一个有速度 - 经过一段时间和大量弹跳后,它们全部都在移动。在间隔期内,我总结所有速度(abs(x)+ abs(y)) - 如果我一开始有8个,它很快就会增长(这必须违反其中一个守恒定律?),但是过了一会儿它停止增长,只是在20左右波动.. 我感到困惑并且不确定是否应该这样做..(注意:在检测到碰撞后,我向后移动第一个球,在微小的步骤中,直到它们不再重叠,然后调用performCollision) - T4NK3R
尝试对每个进行求和(sqrt(vx^2 + vy^2))。 - clinux

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接