幾何計算に関するトピックを紹介します。まずは入力してうごかしてみましょう。
円軌道を描くプログラムです。
sin() と cos() を使って、物体が円周上を移動する軌道を描きます。
float angle = 0; // 現在の角度(ラジアン)
float radius = 200; // 軌道の半径
float cx, cy; // 円の中心座標
void setup()
{
size(500, 500);
cx = width / 2;
cy = height / 2;
background(255);
noStroke();
}
void draw()
{
fill(255, 255, 255, 75);
rect(0, 0, width, height); // 残像を演出
fill(200, 0, 0);
circle(cx, cy, 30);
// 軌道上の点の座標を計算
float x = cx + radius * cos(angle);
float y = cy + radius * sin(angle);
// 点を描く
fill(0);
circle(x, y, 20);
// 角度を少しずつ進める
angle += 0.02;
}
円の軌道は次の数式で描くことができます。
$$ x = cx + r \cos(angle) \\ y = cy + r \sin(angle) $$
cos(angle) と sin(angle) を使って、円周上の点の座標 (x, y) を求めています。angle は現在の角度(単位:ラジアン)です。2π で一周することになります。angle += 0.02 で、毎フレーム角度が進み、円周上を回るようになります。マウスの位置と点(300, 200)間の距離を計算して表示するプログラムです。
void setup()
{
size(800, 600);
}
void draw()
{
background(255);
fill(0);
strokeWeight(4);
circle(300, 200, 25);
circle(mouseX, mouseY, 25);
line(300, 200, mouseX, mouseY);
// 2点間の距離を計算して返す: √((x2 - x1)² + (y2 - y1)²)
// sqrt は、平方根(√)を計算する関数です。
float x1 = 300;
float y1 = 200;
float x2 = mouseX;
float y2 = mouseY;
float l = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
float tx = (x1 + x2) / 2;
float ty = (y1 + y2) / 2;
textSize(36);
text(l, tx, ty);
}
2点 $p_1(x_1, y_1)$ と $p_2(x_2, y_2)$ 間の距離は、
$$ l = \sqrt{(x_2-x_1)^2 + (y_2-y_1)^2} $$
で計算できます。
上記「2点間の距離」を応用して、ある点 $p$ が円の内側にあるか外側にあるかを判定することができます。