10th Floor/programming

From CDOT Wiki
Revision as of 16:44, 8 October 2010 by Corey Angus (talk | contribs) (Collision: sphere to rectangle collision)
Jump to: navigation, search


Sphere to Sphere Collision

    • Each sphere is described by an x and y co-ordinate located in the very center, as well as a radius.
    • If the distance between each sphere is less than the sum of their radius's, then a collision has occurred.
int collision_sphere (x_sphere1, y_sphere1, r_sphere1, x_sphere2, y_sphere2, r_sphere2){
  int collision = 0;
  double distance = √(x_sphere1 - x_sphere2)² + (y_sphere1 - y_sphere2)²; // calculate distance
  if ((r_sphere1 + r_sphere2) > distance){ // compare to sum of radius
    collsion = 1;
  return collsion;

Sphere to Rectangle Collision

    • Sphere is still describes as above. x, y, and radius.
    • Rectangles described as x, y from bottom left corner. As well as width and height.
    • If the value of the sphere's x and y is between the rectangles borders + the radius of the sphere, collision has occurred.
int collision_sphere_rect (x_sphere, y_sphere, r_sphere, x_rect, y_rect, w_rect, h_rect){
  int collision = 0;
  if ( (x_sphere > x_rect) && (x_sphere < (x_rect + w_rect) ){ //potential collision, sphere between rectangle borders on x axis
    if ( (y_sphere > y_rect) && (y_sphere < (y_rect + h_rect) ){ //confirmed collision, sphere also between rectangle borders on y axis
      collision = true;
  return collsion;
    • that's the basic idea. Depending on the direction the sphere is moving you'll have to add or subtract the radius from the comparision, otherwise collision will only be true when half or more of the sphere is within the rectangle.