创建一个类,该类在另一个类创建的点之间绘制线条



我正在制作一个程序,用p5.js为贝塞尔曲线制作动画。我已经创建过一次这个程序,但这次我正在完善它。(我基本上是在复制杰森戴维斯的作品(我希望能够为曲线创建任意数量的控制点。到目前为止,我有一个类,每当我按下按钮时,它都会在我的画布上的随机点创建一个控制点。这就是我所走多远的程度:

let controlPoints = [];
function setup() {
createCanvas(600, 600);
//Adds a button called "Add controlpoint" that calls the function "addControlPoint"
button = createButton('Add controlpoint');
button.position(10, 10);
button.mousePressed(addControlPoint);
//Adds a button called "Remove controlpoint" that calls the function "removeControlPoint"
button = createButton('Remove controlpoint');
button.position(10, 45);
button.mousePressed(removeControlPoint);
}
function draw() {
background(55);
//Draws all of the controlpoints in the array "controlPoints"
for (let i = 0; i < controlPoints.length; i++) {
controlPoints[i].show();
controlPoints[i].overPoint();
}
}
//If the button "Add controlpoint" is pressed create controlpoint att random location
function addControlPoint() {
controlPoints.push(new controlPointBrain(random(width), random(height), 25));
}
//If the button "Remove controlpoint" is pressed remove latest controlpoint added
function removeControlPoint() {
controlPoints.pop();
}

这是我的控制点课程

class controlPointBrain {
constructor(x_, y_, r_) {
this.x = x_;
this.y = y_;
this.r = r_;
}
overPoint() {
//If the controlpoint is over the x-edge stop it from going over
if (this.x >= width) {
this.x = width-(this.r/2);
} else if (this.x < 0) {
this.x = 0+(this.r/2);
}
//If the controlpoint is over the y-edge stop it from going over
if (this.y >= height) {
this.y = height-(this.r/2);
} else if (this.y < 0) {
this.y = 0+(this.r/2);
}
}
show() {
strokeWeight(4);
fill(55);
//Checks if the mouse is over the controlpoint
if (mouseX <= this.x+(this.r/2) && mouseX >= this.x-(this.r/2) &&
mouseY >= this.y-(this.r/2) && mouseY <= this.y+(this.r/2))
{
stroke(55, 255, 50);
} else {
stroke(255, 50, 50);
}
//Draws an ellipse
ellipse(this.x, this.y, this.r);
}
}

现在我想创建一个类/函数,每次添加控制点时,该类/函数都会在最新的控制点和它前面的控制点之间画一条线。是否可以创建一个自动绘制这些线条的类?还是我应该创建一个执行此操作的函数? 对我已经编程的内容的任何有用的批评也将不胜感激!

函数,

每次添加控制点时,都会在最新的控制点和它前面的控制点之间画一条线

那只是最后一点和倒数第二点?您可以从数组的末尾抓取它们并在它们之间画一条线。您可以在迭代点后的绘制循环中执行此操作。

if ( controlPoints.length > 1 ){
let lastPoint = controlPoints[ controlPoints.length - 1 ];
let secondToLastPoint = controlPoints[ controlPoints.length - 2 ];
//draw line between this point and otherPoint
line( lastPoint.x, lastPoint.y, secondToLastPoint.x, secondToLastPoint.y );
}

代码非常整洁,看起来不错。我唯一会做的不同的事情是调用controlPoints[i].overPoint();每一帧。我认为这存在是因为您要移动点?我只会在实际移动一个点后调用该函数。

最新更新