球 - 球碰撞检测 - >反应

Art*_*mix 6 algorithm geometry collision-detection collision

我需要制作一个算法来检测两个球体何时碰撞,以及一个碰撞后瞬间出现的方向.

比方说,想象一下当你在一场比赛中打开你的牌桌时,所有的球都是"随机"相互碰撞.

所以,在开始自己编写代码之前,我在想是否已经实现了这个.

Thx提前!

Cyas.-

cli*_*nux 9

碰撞部分很容易.检查球体中心之间的距离是否小于其半径之和.

至于反弹,你需要交换与垂直于球体碰撞的总速度有关的速度量.(假设你的所有球体都有相同的质量,那么对于不同质量的组合会有所不同)

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:如果你需要更高的准确度,那么在碰撞时你应该计算向后移动两个碰撞球体的距离,使它们只是相互接触,然后触发执行碰撞功能.这样可以确保角度更准确.