Simulating cloth with gravity and collision detection
CS-116B: Graphics Algorithms
Instructor: Rob Bruce
Spring 2016

Collision detection

For each particle in your list, follow steps 1 through 6 below.

Collision detection: Step 1

Step 1: Computing the difference (in X, Y, Z) between the center of the ball and the particle.

particle_to_ball.x = particle_element->pos.x - ball_center.x;
particle_to_ball.y = particle_element->pos.y - ball_center.y;
particle_to_ball.z = particle_element->pos.z - ball_center.z;

Collision detection: Step 2

Step 2: Compute the magnitude of the vector defined in step 1.

Note: The magnitude is equivalent to calculating the Euclidean distance between the center of the ball and the particle.

length_of_particle_to_ball_center = sqrt (particle_to_ball.x * particle_to_ball.x + particle_to_ball.y * particle_to_ball.y + particle_to_ball.z * particle_to_ball.z);

Collision detection: Step 3

Step 3: If the magnitude computed in step 2 is less than the ball radius, the particle has collided with the ball! In such cases, we should project the particle on the ball’s surface (ball center + radius). How? Proceed to step 4!

if (length_of_particle_to_ball_center < ball_radius)
{
  execute step 4 instructions
  execute step 5 instructions
  execute step 6 instructions
}

Collision detection: Step 4

Step 4: Normalize the vector defined by the difference between the particle and the ball center (computed in step 1). Proceed to step 5.

particle_to_ball_normalized.x = particle_to_ball.x / length_of_particle_to_ball_center;
particle_to_ball_normalized.y = particle_to_ball.y / length_of_particle_to_ball_center;
particle_to_ball_normalized.z = particle_to_ball.z / length_of_particle_to_ball_center;

Collision detection: Step 5

Step 5: Now multiple the normalized vector computed in step 4 by the difference between the ball radius and the length of the particle to ball center. This represents the distance the particle must move to be on the surface of the ball relative to the position the particle is now. Proceed to step 6.

particle_to_ball_normalized.x = particle_to_ball_normalized.x * (ball_radius - length_particle_to_ball_center);
particle_to_ball_normalized.y = particle_to_ball_normalized.y * (ball_radius - length_particle_to_ball_center);
particle_to_ball_normalized.z = particle_to_ball_normalized.z * (ball_radius - length_particle_to_ball_center);

Collision detection: Step 6

Step 6: Now add the distance computed in step 5 to the particle’s current position. This moves the particle to the ball's surface.

particle_element->pos.x = particle_element->pos.x + particle_to_ball_normalized.x;
particle_element->pos.y = particle_element->pos.y + particle_to_ball_normalized.y;
particle_element->pos.z = particle_element->pos.z + particle_to_ball_normalized.z;