用EasyX绘制多球碰撞中的碰撞代码

float minDistances2[BallNum][2]; // 记录某个小球,距离它最近的小球的距离,这个小球的下标
        for (i=0;i0] = 9999999;
            minDistances2[i][1] = -1;
        }

        // 求解所有小球两两之间的距离平方
        for (i=0;ifor (j=0;jif (i!=j) // 自己和自己不需要比
                {
                    float dist2;
                    dist2 = (ball_x[i] - ball_x[j])*(ball_x[i] - ball_x[j])
                        + (ball_y[i] - ball_y[j])*(ball_y[i] - ball_y[j]);
                    if (dist20])
                    {
                        minDistances2[i][0] = dist2;
                        minDistances2[i][1] = j;
                    }
                }
            }
        }   

        // 判断球之间是否碰撞
        for (i=0;iif (minDistances2[i][0]<=4*radius*radius) // 最小距离小于阈值,发生碰撞
            {
                j = minDistances2[i][1];
                // 交换速度             
                int temp;
                temp = ball_vx[i]; ball_vx[i] = ball_vx[j]; ball_vx[j] = temp;
                temp = ball_vy[i]; ball_vy[i] = ball_vy[j]; ball_vy[j] = temp;

                minDistances2[j][0] = 999999999; // 避免交换两次速度,又回去了
                minDistances2[j][1] = -1;
            }
        }

你可能感兴趣的:(用EasyX绘制多球碰撞中的碰撞代码)