(13) Detecting collisions

Phuu, when coding the next section of the Astroids game, I realized some things might become a little tricky. Processing has no built in support for collisions, so one have to do it all, or use someone elses code for it. Before showing the code for the game, I thought a small demo on how the code looks like to detect collision between two circles would be in order.... Please copy and paste and run the code below:

void setup() {
  size(848, 480);
}

void draw () {
  int dist;
  background(0);

  // Calculate the distance from center of each circle (i.e. the length of the line that is drawn)
  dist = int(sqrt((mouseX-width/2)*(mouseX-width/2)+(mouseY-height/2)*(mouseY-height/2))); 

  stroke(255);
  // Fill red if the distance is less than 90 pixels (radius is 40 and 50 for the circles) 
  if (dist<90) 
    fill(128, 0, 0, 128); 
  else 
    noFill();

  // Draw circle at mouse
  ellipse(mouseX, mouseY, 100, 100);
  // Draw circle at center
  ellipse(width/2, height/2, 80, 80);
  
  // Rest is just text for the calculation
  fill(255);
  text("X=" + width/2 + " Y=" + height/2, width/2, height/2);
  text("X=" + mouseX + " Y=" + mouseY, mouseX-35, mouseY);
  ellipse(mouseX, mouseY, 2, 2);
  ellipse(width/2, height/2, 2, 2);
  stroke(128);
  line(mouseX, mouseY, width/2, height/2);
  text("dist = sqrt(" + "(" + mouseX + "-" + width/2 + ")" + "*" + "(" + mouseX + "-" + width/2 + ")" + "+" +  
    "(" + mouseY + "-" + height/2 + ")" + "*" + "(" + mouseY + "-" + height/2 + "))", 15, 15);
  text("dist = sqrt(" + "(" + (mouseX-width/2) + ")" + "*" + "(" + (mouseX-width/2) + ")" + "+" +  
    "(" + (mouseY-height/2) + ")" + "*" + "(" + (mouseY-height/2) + "))", 15, 35);
  text("dist = sqrt(" + "(" + (mouseX-width/2)*(mouseX-width/2) + ")" + "+" +  
    "(" + (mouseY-height/2)*(mouseY-height/2) + "))", 15, 55);

  text("dist = " + dist, 15, 75);
}


This code draws two circles, one in the center and one at the mouse. To calculate the distance between them the classic Pythagoras' theorem is used. The square root our of the cube of the horizontal and vertical distances is calculated and if the distance is less than the sum of the two radius's, we have a collision. Too complex? Consider this explanation on how to detect if a triangle and circle collides.... quite complex.  Circle-Circle seems quite easy after reading that.


No comments:

Post a Comment