16,472
社区成员
发帖
与我相关
我的任务
分享
double lenX = ball1->x + ball1->vx - ball2->x - ball2->vx; //计算下一时刻两小球位置,判断是否相撞
double lenY = ball1->y + ball1->vy - ball2->y - ball2->vy;
double dirX = ball1->x - ball2->x; //用于计算球1与球2位置的向量
double dirY = ball1->y - ball2->y;
double std_len = pow(dirX, 2) + pow(dirY, 2);
double monster_len = pow(lenX, 2) + pow(lenY, 2);
if(monster_len <= pow(MONSTER_SIZE_X, 2))
{
double cos = dirX / sqrt(std_len); //向量长度标准化
double sin = dirY / sqrt(std_len); // 接触面法向量n(cos,sin), 切向向量t(sin, -cos)
double v1t = ball1->vx * sin - ball1->vy * cos;
double v2t = ball2->vx * sin - ball2->vy * cos;
double v1n = ball1->vx * cos + ball1->vy * sin;
double v2n = ball2->vx * cos + ball2->vy * sin;
while(abs(v1n - v2n) <= 1) //希望能防止由于碰撞后速度小于1,造成(int)后速度变为0,不发生碰撞
{
v1n *= 1.1;
}
ball1->vx = v1t * sin + v2n * cos;
ball2->vx = v2t * sin + v1n * cos;
ball1->vy = v1t * -1 * cos + v2n * sin;
ball2->vy = v2t * -1 * cos + v1n * sin;