簡體   English   中英

使用 p5.js 在路徑上移動對象

[英]Moving an object on a path using p5.js

我正在嘗試編寫一個代碼,在 HTML 畫布中模擬此視頻中發生的情況。

我的代碼的不同之處在於每次頁面加載或刷新時,兩個圓的半徑都是隨機生成的。 我需要“行星”以相同的速度沿着它們各自的圓周運動。

我正在使用 p5.js 繪制到畫布上。 p5.j​​s 中是否有根據路徑繪制對象的東西,在我的例子中是一個圓形的路徑?

我瀏覽了參考資料並遇到了向量,但我不太明白它們的作用。

到目前為止我的代碼:

var w = window.innerWidth;
var h = window.innerHeight;
var r1, r1;
var d;
var x1, x2, y1, y2;
var angle = Math.PI / 4;

function setup() {
    // canvas setup
    createCanvas(w, h);
    background(255);
    angleMode(RADIANS);

    // randomly generated radiuses 
    r1 = Math.floor(Math.random() * (h/2-300)) + 300;
    r2 = Math.floor(Math.random() * (200-100)) + 100;

    // drawing the two ellipses
    ellipseMode(CENTER);
    noFill();
    ellipse(w/2, h/2, r1*2, r1*2);
    ellipse(w/2, h/2, r2*2, r2*2);

}

function draw() {

    // points on the circles
    x1 = (r1 * (Math.cos(angle))) + (w/2);
    y1 = (h/2) - (r1 * (Math.sin(angle)));
    x2 = (r2 * (Math.cos(angle))) + (w/2);
    y2 = (h/2) - (r2 * (Math.sin(angle)));

    // drawing two circles at those points
    ellipseMode(CENTER);
    noStroke();
    fill('rgb(140, 140, 140)');
    ellipse(x1, y1, 20, 20);
    ellipse(x2, y2, 20, 20);

    // randomly generated color for the line
    var r = random(0, 255);
    var g = random(0, 255);
    var b = random(0, 255);
    stroke(r, g, b);
    strokeWeight(1);
    // drawing the line that connects the two points
    line(x1, y1, x2, y2);

    // animation????
    angle = angle + (10 * (Math.PI / 180));

}

最后一行的問題在於它創建了均勻的空間線,而不是視頻中創建的模式。

如果兩顆行星以相同的角度增量移動,它們將始終保持一種關系,從而在它們之間形成一條均勻間隔的線。

為了使它們之間連接的線穿過中心,它們必須具有不同的增量值。 您必須保持兩個不同的角度值以及每個角度的步長(或速度)。

對於視頻中的示例,速度比為 1:2.247,基於地球和金星繞太陽的日比之間的真實世界關系。 由於它們的速度不同,它們之間的線現在將交叉並產生五角星形圖案。

我不知道 P5.js,所以我在下面添加了一個普通的 JavaScript 示例,如果需要 P5,可以將其視為偽代碼。 從中您將能夠看到如何以可變速度計算兩個位置。

例子

折斷

 var ctx = c.getContext("2d"), ratio = 2.247, // earth:venus ratio 1:2.247 angle1 = 0, // planet 1 current angle angle2 = 0, // planet 2 current angle dlt = 0.05, // angle step (speed) radius1 = 150, // radius path for planet 1 radius2 = 100, // radius path for planet 2 cx = c.width*0.5, // center canvas cy = c.height*0.5, t = 503; // abort animation per # of frames ctx.strokeStyle = "rgba(0,120,255,0.5)"; (function loop() { var x1, y1, x2, y2; x1 = cx + Math.cos(angle1) * radius1; // current (x,y) for planet 1 y1 = cy + Math.sin(angle1) * radius1; x2 = cx + Math.cos(angle2) * radius2; // current (x,y) for planet 2 y2 = cy + Math.sin(angle2) * radius2; ctx.beginPath(); // draw line ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); angle1 += dlt; // increase angle planet 1 angle2 += dlt * ratio; // increase angle planet 2 per ratio if (t--) requestAnimationFrame(loop) })()
 <canvas id=c height=300></canvas>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM