# October 8

Here are some example programs that illustrate how to:

• Calculate the distance between two points (such as the cursor and the center of the screen)
• Calculate the orientation of a line between two points
• Constrain a particle to be limited to a circular region

(This is essentially a review of the Pythagorean theorem and some basic trigonometry.)

## Orientation of a Line

``````var clampRadius = 130;

function setup() {
createCanvas(400, 400);
}

function draw() {
background(255, 200, 200);

// The center of the canvas
var cx = width / 2;
var cy = height / 2;

// The horizontal and vertical components of the
// distance from the cursor to the canvas center
var dx = mouseX - cx;
var dy = mouseY - cy;

// Ancient Greek technology (Pythagoras):
// The distance from the cursor to the canvas center
var mouseRadius = sqrt(dx*dx + dy*dy);

// atan2() computes the inverse tangent for all quadrants.
// That is, the angle whose tangent is dy/dx.
// Yes the arguments are given in the order shown.
var orientation = atan2(dy, dx);

// A line is computed with the desired radius,
// and the mouse-driven orientation.
var clampedDx = clampRadius * cos(orientation);
var clampedDy = clampRadius * sin(orientation);

strokeWeight(1);
stroke(0,0,0, 45);
line (cx, cy, cx+dx, cy+dy);
strokeWeight(2);
stroke(0,0,0, 255);
line (cx, cy, cx+clampedDx, cy+clampedDy);

noFill();

// Draw the orientation text angle.
push();
translate(cx, cy);
rotate(orientation);
fill(0);
noStroke();
var displayString = "Orientation: " + nf(degrees(orientation),1,2);
text (displayString, 0, 20);
pop();

}
``````

## Constrain a Particle to a Circle

``````var bugs = [];

function setup() {
createCanvas(400, 400);
for (var i = 0; i < 40; i++) {
bugs.push(new JitterBug());
}
}

function draw() {
background(255, 200, 200);

var cx = width / 2;
var cy = height / 2;
noFill();

for (var i = 0; i < bugs.length; i++) {
bugs[i].move();
bugs[i].display();
}

}

// Jitter class
function JitterBug() {
this.x = width / 2;
this.y = height / 2;
this.diameter = 16;
this.vx = 0.2*random(-1, 1);
this.vy = 0.2*random(-1, 1);

this.move = function() {
var cx = width / 2;
var cy = height / 2;
var dx = this.x - cx;
var dy = this.y - cy;
var radius = sqrt(dx * dx + dy * dy);
this.x += this.vx;
this.y += this.vy;
} else {