pythagorean theorem

The Pythagorean theorem has a bunch of uses, but the most important thing for us to remember is that we can use it to calculate the length of any side of a right-angle triangle. Or, in practical terms, we can use it to calculate the distance between any two points in space.

This comes in very handy when programming, particularly when doing collision detection. In Processing, you can use dist(), an implementation of the Pythagorean theorem used to calculate the distance between two sets of coordinates.

```//----------------------------
// variables
int staticX;
int staticY;
int staticSize;
int mobileSize;

//----------------------------
void setup() {
// set up the applet
size(300, 300);
smooth();
frameRate(30);
noCursor();
noStroke();

// set the ball params
staticSize = (int)random(10, 100);
mobileSize = (int)random(10, 100);
staticX = (int)random(staticSize, width - staticSize);
staticY = (int)random(staticSize, height - staticSize);
}

//----------------------------
void draw() {
// clear the screen
if (areColliding()) {
background(color(random(200, 255), 0, 0));
} else {
background(0);
}

// draw the static ball
fill(#505EEA);
ellipse(staticX, staticY, staticSize, staticSize);

// draw the moving ball
fill(#7BD14A);
ellipse(mouseX, mouseY, mobileSize, mobileSize);
}

//----------------------------
boolean areColliding() {
float currDistance = sqrt(pow(staticX - mouseX, 2) + pow(staticY - mouseY, 2));
// alternatively, use the built-in dist(...) function
//float currDistance = dist(staticX, staticY, mouseX, mouseY);
float minDistance = staticSize/2 + mobileSize/2;

if (currDistance < minDistance) {
return true;
}
return false;
}
```  Math For Artists Who Now Need to Program

Elie Zananiri
ITP DriveBy
1 Oct 2008