Collision detection for multiple small balls ~~~~~~~~~
The entire code is as follows:
M. _ visible = 0;
Function setMc (m_width, w, h, speed ){
Stage_w = w-m_width;
Stage_h = h-m_width;
For (I = 1; I <11; I ++ ){
M = m. duplicateMovieClip ("m" + I, I );
M_x = m_width/2 + random (stage_w );
M_y = m_width/2 + random (stage_h );
If (I = 1 ){
M. _ x = M_x;
M. _ y = M_y;
}
If (I> 1 ){
For (j = 1; j <I; j ++ ){
If (Math. sqrt (this ["m" + j]. -x-M_x) * (this ["m" + j]. -x-M_x) + (this ["m" + j]. -y-M_y) * (this ["m" + j]. _ y-M_y) <m_width ){
I --;
Break;
}
}
If (j = I ){
M. _ x = M_x;
M. _ y = M_y;
}
}
// The above is a random arrangement of non-overlapped small balls within a certain range.
M. rotation = random (2 * Math. PI );
M. xspeed = speed;
M. yspeed = speed;
// Initial speed and angle of each ball
M. onEnterFrame = function (){
This. _ x + = this. xspeed * Math. cos (this. rotation );
This. _ y + = this. yspeed * Math. sin (this. rotation );
//--------------
For (I = 1; I <11; I ++ ){
If (I = this. _ name. substr (1, this. _ name. length )){
Continue;
} Else if (Math. sqrt (this. _ y-_ root ["m" + I]. _ y) * (this. _ y-_ root ["m" + I]. _ y) + (this. _ x-_ root ["m" + I]. _ x) * (this. _ x-_ root ["m" + I]. _ x) <= m_width ){
This. rotation = Math. atan2 (this. _ y-_ root ["m" + I]. _ y, this. _ x-_ root ["m" + I]. _ x );
This. xspeed = speed;
This. yspeed = speed;
This. _ x + = this. xspeed * Math. cos (this. rotation );
This. _ y + = this. yspeed * Math. sin (this. rotation );
Break;
}
// Each ball is used to determine the contact between all other small balls in the scenario. The contact here is determined by distance.
}
//---------------
If (this. _ x <= m_width/2 ){
This. _ x = m_width/2 +. 1;
This. xspeed * =-1;
} Else if (this. _ x> = 300-m_width/2 ){
This. _ x = 300-m_width/2-.1;
This. xspeed * =-1;
} Else if (this. _ y <= m_width/2 ){
This. _ y = m_width/2 +. 1;
This. yspeed * =-1;
} Else if (this. _ y> = 300-m_width/2 ){
This. _ y = 300-m_width/2-.1;
// Here-. 1 is used to prevent boundary problems. You can delete this sentence to check whether the cause is self-thinking.
This. yspeed * =-1 ;}
};
// Here is the judgment of the ball hitting the boundary
}
}
SetMc (m. _ width, 300,300, 5); // The parameters are respectively the width of the ball,