p5.j​​s沿着多边形的轨迹移动物体

时间:2018-01-27 20:00:13

标签: javascript canvas p5.js

我刚开始学习p5和画布。如果这是一个愚蠢的问题,那就很抱歉。

我在网上发现了gif,并决定在p5.js中重复这一点。所以我已经编写了代码来生成下面的图片。

var shapes = [];
function setup() {
    createCanvas(windowWidth, windowHeight);
    for(var i = 1; i < 12; i++){
        shapes.push(new Shape(i));
    }
    console.log(shapes);
}

function draw(){
    background(255);
    stroke('red')
    for(var i = 0; i < shapes.length; i++){
        shapes[i].show();
        shapes[i].moveDot();
    }
}

function Shape(n) {
    colors = ['','red','#cd8410','#cdcb10','#8dcd10','#56cea8','#47c4cc','#479ccc','#476acc','#5d47cc','#9847cc','#b547cc','#cc47a2','#cc4760'];
    this.x = width/2;
    this.y = height/2;
    this.vertices = n+2;
    this.spaceBetween = 20;
    this.edge = this.spaceBetween/(cos(PI/5)/(2*sin(TWO_PI/10))-cos(PI/4)/(2*sin(TWO_PI/8)));
    this.oR = this.edge / ( 2 * sin(TWO_PI/ (2 * this.vertices) ));
    this.iR = this.oR * cos(PI/this.vertices);
    this.degrees = asin(this.iR / this.oR);

    this.dotX = this.x;
    this.dotY = this.y + this.iR;
    this.dotSpeed = 3;
    this.dotPCT = 0;

    this.vcord = [];
    for(var i = 0; i < TWO_PI; i+= TWO_PI / this.vertices){
        this.vcord.push([this.x + cos(this.degrees + i) * this.oR, this.y + sin(this.degrees + i) * this.oR]);
    }

    this.show = ()=>{
        stroke(colors[n%14]);
        noFill();
        beginShape();
        for(var i = 0; i < this.vcord.length; i++){
            vertex(this.vcord[i][0], this.vcord[i][1]);
        }
        endShape(CLOSE);
        noStroke();
        fill(0)
        ellipse(this.dotX, this.dotY, 10);
    }

    this.moveDot = ()=>{

    }
}

enter image description here

现在我的目标是让每个点沿其多边形的轨迹移动。我可以访问this.vcord数组中多边形的每个坐标,但我无法弄清楚如何以正确的方式进行。

1 个答案:

答案 0 :(得分:1)

您可以使用lerp()功能获得两个其他点之间某个百分比的点数。更多信息可以在the reference找到。

var xOne = 10;
var yOne = 10;
var xTwo = 100;
var yTwo = 100;

var midX = lerp(xOne, xTwo, 0.5);
var midY = lerp(yOne, yTwo, 0.5);

ellipse(midX, midY, 20, 20);

然后只需修改您传入lerp()函数的第三个值,即在其他两个点之间移动点。提示:sin()cos()是您的朋友。

如果你无法让它发挥作用,我建议你breaking your problem down into smaller pieces并一次一张。换句话说:不要试图让它在你的完整程序中运行。相反,创建一个只做一件事的小示例草图。尝试使用lerp()函数显示在两个硬编码点之间移动的点。然后添加第三个硬编码点。以这样的小步骤向前迈进。然后,如果您遇到问题,可以发布MCVE以及更具体的问题。祝你好运!

(另外,如果您计划在某个地方发布作品,请注明the original artist。)