今天我們要來比較前兩篇文章

p5.js 基礎教學(一) –– 座標與旋轉圖案

p5.js 基礎教學(二) –– rotate 和 translate

同樣都是實現繞著鼠標進行圓周運動的四個圓圈,到底有什麼不同呢?

不同的地方在於,基礎教學(二) 使用 rotatetranslate,會導致整個座標系統會隨時間移動,但 基礎教學(一) 的座標系統是固定的,因此要用比較複雜的數學方法來計算圓圈的圓周運動軌跡。

如果要驗證這一件事情,我們可以試著在這兩個作品上面畫上座標的格線,我們可以使用 line 函數繪製直線,來完成這一個任務。

line 函數可接收四個參數 line(x1, y1, x2, y2),分別為起點的 xy 座標,和終點的 xy 座標。

我們可以用 for 迴圈輕鬆建構一個座標格線:

function setup() {
	createCanvas(windowWidth, windowHeight);
	background(100);
}

var gridSpacing = 50; // 設定每 50 px 就畫一條格線

function createGrid() { for (var x = -width; x < width; x += gridSpacing) { for (var y = -height; y < height; y += gridSpacing) { stroke(200); // 設定線的顏色為灰色 strokeWeight(1); // 設定線的寬度為1 line(x, -height, x, height); // 畫出垂直線 line(-width, y, width, y); // 畫出水平線 } } }

function draw() { background(100, 100); createGrid(); }

以下為繪製結果:

Imgur

現在我們將這個格線畫在 基礎教學(一)基礎教學(二) 的兩個作品中。

基礎教學(一) 作品:

function setup() {
	createCanvas(windowWidth, windowHeight);
	background(100);
}

function vector_rotation(x,y,angle) { return [cos(angle)x-sin(angle)y,sin(angle)x+cos(angle)y]; }

var gridSpacing = 50;

function createGrid() { for (var x = -width; x < width; x += gridSpacing) { for (var y = -height; y < height; y += gridSpacing) { stroke(200); strokeWeight(1); line(x, -height, x, height); line(-width, y, width, y); } } }

function draw() { background(100, 100); createGrid(); let v = PI / 80 * frameCount; let [x1, y1] = vector_rotation(100, 0, v); let [x2, y2] = vector_rotation(-100, 0, v); let [x3, y3] = vector_rotation(0, 100, v); let [x4, y4] = vector_rotation(0, -100, v);

let y = mouseY; let x = mouseX; circle(x+x1, y+y1, 20); circle(x+x2, y+y2, 20); circle(x+x3, y+y3, 20); circle(x+x4, y+y4, 20); }

動畫呈現:

Imgur

基礎教學(二) 作品:

function setup() {
	createCanvas(windowWidth, windowHeight);
	background(100);
}

var gridSpacing = 50;

function createGrid() { for (var x = -2width; x < 2width; x += gridSpacing) { for (var y = -2height; y < 2height; y += gridSpacing) { stroke(200); strokeWeight(1); line(x, -2height, x, 2height); line(-2width, y, 2width, y); } } }

function draw() { background(100,100); translate(mouseX, mouseY); rotate(PI / 80 * frameCount); createGrid(); circle(100, 0, 20); circle(-100, 0, 20); circle(0, 100, 20); circle(0, -100, 20); }

動畫呈現:

Imgur